Id
stringlengths 1
5
| Tags
stringlengths 3
75
| Title
stringlengths 15
150
| CreationDate
stringlengths 23
23
| Body
stringlengths 51
27.6k
| Answer
stringlengths 42
31k
|
---|---|---|---|---|---|
12549 | |arduino-yun|ssh| | How to copy files from local computer to Yun with scp? | 2015-06-11T07:19:15.727 | <p>I need to transfer files from my local machine to my Arduino Yun.</p>
<p>I have tried:</p>
<pre><code>scp /Users/SSCirrus/Documents/index.html root@arduino.local:/root
scp ~/Users/SSCirrus/Documents/index.html root@arduino.local:/root
# No such file or directory (referring to my desktop)
</code></pre>
<p>I have confirmed that the filepath is accurate. What's wrong here?</p>
| <p>Try <code>~/Documents/index.html</code></p>
<p>The <code>~</code> represents the current user's home directory, so <code>~/Documents</code> is the Documents folder for the current user. It means you don't have to make sure you have spelled the user's home directory exactly right.</p>
<p>Other options are:</p>
<ul>
<li><code>$HOME/Documents/index.html</code></li>
<li><code>Documents/index.html</code> (if you are in your home directory)</li>
<li><code>cd ~/Documents</code> then just use <code>index.html</code></li>
</ul>
<p>... the list goes on ...</p>
|
12551 | |sensors|bluetooth|interrupt| | Running multiple tasks at once | 2015-06-11T10:03:05.770 | <p>For a school project we're working on a wearable device to track people's movement and heart rate. We use an Arduino Pro Mini with a heartbeat sensor and an accelerometer. The wearable device uses Bluetooth to send data, but only once or twice a day to save battery.</p>
<p>The problem we currently face is having the Arduino keep track of the accelerometer data while also reading the heartbeat sensor on a select interval. See the pseudo-code underneath. In what way (preferably without implementing too many libraries) could we merge these two loops so the accelerometer is read non-stop while keeping an interval (of about 30 minutes) between the heart beat readings? Any input would be greatly appreciated and if needed I can provide additional information.</p>
<pre><code>void loop() {
// Heartbeat sensor loop
while (array is not full) {
delay(30 minutes);
heartbeatArray[index++] = readHeartbeat();
}
sendData_Bluetooth(heartbeatArray);
emptyArray();
// End of heartbeat sensor loop
// Accelerometer loop
while (true)
if (readAccelerometerData > limit)
sendAlert();
// End of accelerometer loop
}
</code></pre>
| <p>See <a href="https://electronics.stackexchange.com/a/67091/10371">https://electronics.stackexchange.com/a/67091/10371</a> (Since this is another stack exchange site, I won't copy the info)</p>
<p>The short answer is to use timers that trigger interrupts. Examples are shown in the link.</p>
|
12558 | |arduino-uno|c|sketch|debugging|code-optimization| | How to read code from Arduino Uno to Arduino IDE? | 2015-06-11T17:31:17.797 | <p>we can upload a code into Arduino UNO from our computers, but how about reading code? Can we read and get C codes from compiled codes from Arduino hardwares? My second question is that will we read these compiled codes on Arduino ZERO's debug port, which will be a new product for us as developers?</p>
| <blockquote>
<p>Can we read and get C codes from compiled codes from Arduino hardwares?</p>
</blockquote>
<p>While it is possible, even trivial, to disassemble machine code, it is very difficult to convert the assembly code into a higher-level language, and essentially impossible to turn it back into an exact copy of the source code it came from. There simply isn't enough information in the machine code to do so.</p>
<blockquote>
<p>My second question is that will we read these compiled codes on Arduino ZERO's debug port, which will be a new product for us as developers?</p>
</blockquote>
<p>The debug port will work in tandem with appropriate software that will already have access to the source code, so this is not a method for conversion either.</p>
|
12571 | |i2c| | Trouble making TMP102 work with any ADD0 other than ground | 2015-06-11T22:17:50.933 | <p>I'm trying to get an Arduino Uno to run four sensors (all I2C). The first two are TMP102 temperature sensors. The address is controlled by tying the ADD0 pin to GND, VCC, SDA, or SCL (four possible addresses, without multiplexing). I get it to receive data just fine through the GND setting. </p>
<p>I wrote some code to collect from two, but before I was even talking to the second one, plugging it in causes the data stream from the GND one to stop. Unplugging it from the breadboard makes it work again. Either sensor in either location on the breadboard will work fine, as long as it's addressed as ground. Neither sensor will, even by itself, work with any other address. I tried some other sketches from the net (one attached below that should read from any of four different sensors), but all have the same issue.</p>
<pre><code>#include <Wire.h>
byte res;
byte msb;
byte lsb;
int val;
void setup()
{
Serial.begin(9600);
Wire.begin();
}
void loop()
{
res = Wire.requestFrom(72,2);
if (res == 2) {
msb = Wire.read(); /* Whole degrees */
lsb = Wire.read(); /* Fractional degrees */
val = ((msb) << 4); /* MSB */
val |= (lsb >> 4); /* LSB */
Serial.print( "72:");
Serial.println(val*0.0625);
delay(1000);
}
res = Wire.requestFrom(73,2);
if (res == 2) {
msb = Wire.read(); /* Whole degrees */
lsb = Wire.read(); /* Fractional degrees */
val = ((msb) << 4); /* MSB */
val |= (lsb >> 4); /* LSB */
Serial.print( "73:");
Serial.println(val*0.0625);
delay(1000);
}
res = Wire.requestFrom(74,2);
if (res == 2) {
msb = Wire.read(); /* Whole degrees */
lsb = Wire.read(); /* Fractional degrees */
val = ((msb) << 4); /* MSB */
val |= (lsb >> 4); /* LSB */
Serial.print( "74:");
Serial.println(val*0.0625);
delay(1000);
}
res = Wire.requestFrom(75,2);
if (res == 2) {
msb = Wire.read(); /* Whole degrees */
lsb = Wire.read(); /* Fractional degrees */
val = ((msb) << 4); /* MSB */
val |= (lsb >> 4); /* LSB */
Serial.print( "75:");
Serial.println(val*0.0625);
delay(1000);
}
}
</code></pre>
<p>Breadboard:
(image link: the forum kept crashing when I tried to upload the image directly)
<a href="https://www.sugarsync.com/pf/D333436_95042359_6938296" rel="nofollow">https://www.sugarsync.com/pf/D333436_95042359_6938296</a></p>
<p>Thanks!</p>
| <p>You see that little solder jumper block on the breakout board labelled "ADD0"? You need to remove the solder from that. It's currently connected in a pre-defined position and you trying to use the ADD0 pin is conflicting with that.</p>
|
12576 | |programming|c| | Conver char value to variable? | 2015-06-12T01:58:20.760 | <p>I want to pass the preprocessor values(AT commands) to the Serial.println function. Im trying TCP connection using arduino-SIM900A. I've declared all AT commands to each preprocessor variables like below</p>
<pre><code>#define A "AT\r"
#define B "AT+CPIN?\"
...
</code></pre>
<p>I've assigned all preprocessor variables in char array and pass it into Serial.print using for loop.</p>
<pre><code>char varAT[12]={'A','B'....};
for(int i=0;i<=12;i++)
{
Serial.print(varAT[i]);
}
</code></pre>
<p>Its not printing AT, instead it print preprocessor variable name A. I searched the google how to convert char value to variable, in C there is a function called "eval". Using eval we can acheive, but it wont work in arduino lang. How to solve this?</p>
<p>Thanks. </p>
| <p>Ok, first, <code>char varAT[12]</code> indicates an array of 12 characters. </p>
<p>Second, quotes indicate literals - 'A' means, literally, the character 'A'. Variables and constants are without quotes (same way you use <code>i</code>).</p>
<p>I think you mean:</p>
<pre><code>char *varAT[12]={A,B....};
</code></pre>
<p>Also, your constant <code>B</code> is invalid - I think you meant for it to end in <code>\r"</code>, not <code>\"</code>.</p>
|
12586 | |arduino-uno|serial| | Intializing Serial crashes UNO | 2015-06-12T10:49:44.643 | <p>I have a somewhat large sketch that uses the <code>Adafruit_ssd1306</code>(I2C) library for a 128X64 LCD. The sketch is a designed to be an alarm clock. When I upload the sketch with out initializing serial, it works as designed. However if I do intialize serial:</p>
<pre><code>Serial.begin(9600);
</code></pre>
<p>the program fails to run on my UNO. After many hours of troubleshooting I noticed I have several large char arrays that may be the culprit.</p>
<pre><code>const char *menusDisplay[] = {"1. Alarm-is Off", "2. Month", "3. Hour", "4. Minute", "5. Exit", "6. Alarm Set", NULL};
const char *months[] = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep" , "Oct", "Nov", "Dec", NULL};
const int days[] = {31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
</code></pre>
<p>The months array as 12 elements. If I shorted it down to 2 elements and upload the programs with serial initialized, the program runs. At first I thought is was a memory leak in perhaps the <code>Adafruit_ssd1306</code>. But I also have another LCD library <code>Adafruit_ssd1306syp</code> that the issue occurred too. So that ruled out those libraries.</p>
<p>When I compile the sketch without Serial:</p>
<pre><code>Sketch uses 16,846 bytes (52%) of program storage space. Maximum is 32,256 bytes.
Global variables use 737 bytes (35%) of dynamic memory, leaving 1,311 bytes for local variables. Maximum is 2,048 bytes.
</code></pre>
<p>With Serial:</p>
<pre><code>Sketch uses 17,862 bytes (55%) of program storage space. Maximum is 32,256 bytes.
Global variables use 910 bytes (44%) of dynamic memory, leaving 1,138 bytes for local variables. Maximum is 2,048 bytes.
</code></pre>
<p>Any ideas of what may be going on? I would load the sketch but its very large. If needed, I can try to cut it down and reproduce the issue.</p>
| <p>@EdgarBonet pointed out in a comment, I need to check my dynamic ram, which could be used by the Heap and Stack. The class can be found <a href="http://playground.arduino.cc/Code/AvailableMemory" rel="nofollow">here</a> to measure ram usage. Since links can die, here is the code:</p>
<p>Here is the header:</p>
<pre><code>/* MemoryFree.h */
// MemoryFree library based on code posted here:
// http://www.arduino.cc/cgi-bin/yabb2/YaBB.pl?num=1213583720/15
// Extended by Matthew Murdoch to include walking of the free list.
#ifndef MEMORY_FREE_H
#define MEMORY_FREE_H
#ifdef __cplusplus
extern "C" {
#endif
int freeMemory();
#ifdef __cplusplus
}
#endif
#endif
</code></pre>
<p>Here is the .cpp</p>
<pre><code>/* MemoryFree.cpp */
#if (ARDUINO >= 100)
#include <Arduino.h>
#else
#include <WProgram.h>
#endif
extern unsigned int __heap_start;
extern void *__brkval;
/*
* The free list structure as maintained by the
* avr-libc memory allocation routines.
*/
struct __freelist {
size_t sz;
struct __freelist *nx;
};
/* The head of the free list structure */
extern struct __freelist *__flp;
#include "MemoryFree.h"
/* Calculates the size of the free list */
int freeListSize() {
struct __freelist* current;
int total = 0;
for (current = __flp; current; current = current->nx) {
total += 2; /* Add two bytes for the memory block's header */
total += (int) current->sz;
}
return total;
}
int freeMemory() {
int free_memory;
if ((int)__brkval == 0) {
free_memory = ((int)&free_memory) - ((int)&__heap_start);
} else {
free_memory = ((int)&free_memory) - ((int)__brkval);
free_memory += freeListSize();
}
return free_memory;
}
</code></pre>
<p>From this I was able to see how much ram was used. Of the avialable 2k, I had only 100k left. So now I know why my program is crashing, I need a solution. The solution was to store the static content in program memory (PROGMEM):</p>
<pre><code>const char* const months[] PROGMEM =
{
"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
};
const uint8_t days_of_month[] PROGMEM =
{
31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31
};
</code></pre>
|
12587 | |programming|time|millis| | How can I handle the millis() rollover? | 2015-06-12T11:16:30.810 | <p>I need to read a sensor every five minutes, but since my sketch also has
other tasks to do, I cannot just <code>delay()</code> between the readings. There
is the <a href="http://www.arduino.cc/en/Tutorial/BlinkWithoutDelay" rel="noreferrer">Blink without
delay</a> tutorial
suggesting I code along these lines:</p>
<pre class="lang-c++ prettyprint-override"><code>void loop()
{
unsigned long currentMillis = millis();
// Read the sensor when needed.
if (currentMillis - previousMillis >= interval) {
previousMillis = currentMillis;
readSensor();
}
// Do other stuff...
}
</code></pre>
<p>The problem is that <code>millis()</code> is going to roll over back to zero after
roughly 49.7 days. Since my sketch is intended to run for longer
than that, I need to make sure the rollover does not make my sketch
fail. I can easily detect the rollover condition
(<code>currentMillis < previousMillis</code>), but I am not sure what to do then.</p>
<p>Thus my question: what would be the proper/simplest way to handle the
<code>millis()</code> rollover?</p>
| <p>I loved this question, and the great answers it generated. First a quick comment on a previous answer (I know, I know, but I don't have the rep to comment yet. :-).</p>
<p>Edgar Bonet's answer was amazing. I've been coding for 35 years, and I learned something new today. Thank you. That said, I believe the code for <em>"What if I really need to track very long durations?"</em> breaks unless you call millis64() at least once per rollover period. Really nitpicky, and unlikely to be an issue in a real-world implementation, but there you go.</p>
<p>Now, if you really did want timestamps covering any sane time range (64-bits of milliseconds is about half a billion years by my reckoning), it looks simple to extend the existing millis() implementation to 64 bits.</p>
<p>These changes to attinycore/wiring.c (I'm working with the ATTiny85) seem to work (I'm assuming the code for other AVRs is very similar). See the lines with the //BFB comments, and the new millis64() function. Clearly it's going to be both bigger (98 bytes of code, 4 bytes of data) and slower, and as Edgar pointed out, you almost certainly can accomplish your goals with just a better understanding of unsigned integer math, but it was an interesting exercise.</p>
<pre><code>volatile unsigned long long timer0_millis = 0; // BFB: need 64-bit resolution
#if defined(__AVR_ATtiny24__) || defined(__AVR_ATtiny44__) || defined(__AVR_ATtiny84__)
ISR(TIM0_OVF_vect)
#else
ISR(TIMER0_OVF_vect)
#endif
{
// copy these to local variables so they can be stored in registers
// (volatile variables must be read from memory on every access)
unsigned long long m = timer0_millis; // BFB: need 64-bit resolution
unsigned char f = timer0_fract;
m += MILLIS_INC;
f += FRACT_INC;
if (f >= FRACT_MAX) {
f -= FRACT_MAX;
m += 1;
}
timer0_fract = f;
timer0_millis = m;
timer0_overflow_count++;
}
// BFB: 64-bit version
unsigned long long millis64()
{
unsigned long long m;
uint8_t oldSREG = SREG;
// disable interrupts while we read timer0_millis or we might get an
// inconsistent value (e.g. in the middle of a write to timer0_millis)
cli();
m = timer0_millis;
SREG = oldSREG;
return m;
}
</code></pre>
|
12589 | |arduino-due|servo|wires| | Arduino Servo circuit by example | 2015-06-12T11:17:52.490 | <p>I have an Arduino program that uses the <a href="https://github.com/ivanseidel/ArduinoThread" rel="nofollow noreferrer">Thread library</a> to create two concurrent threads, where:</p>
<ul>
<li>Thread #1 blinks an LED every 500ms; and</li>
<li>Thread #2 blinks another LED every 250ms</li>
</ul>
<p>I wired things up, flashed the program to my Arduino Due, and it ran beautifully.</p>
<p>I am now trying to add a 3rd thread that <a href="http://www.arduino.cc/en/Tutorial/Sweep" rel="nofollow noreferrer">sweeps</a> a servo back and forth.</p>
<p>Here's my design:</p>
<p><img src="https://i.stack.imgur.com/kIYK9.png" alt="enter image description here"></p>
<p>And the schematic that Fritzing generated for me:</p>
<p><img src="https://i.stack.imgur.com/VSuFE.png" alt="enter image description here"></p>
<p>And an accompanying actual picture of the wire up:</p>
<p><img src="https://i.stack.imgur.com/HjUyc.jpg" alt="enter image description here"></p>
<p>If you can see it, I've rigged Pin 10 as an <code>OUTPUT</code>, and attached the servo's signal line to Pin 9. Here's the code:</p>
<pre><code>#include <Thread.h>
#include <ThreadController.h>
#include <Servo.h>
int SERVO_SIGNAL_PIN = 9;
int SERVO_PWR_PIN = 10;
int LED_1_PIN = 12;
int LED_2_PIN = 13;
Servo servo;
int pos = 0;
static bool LED_1_STATUS = false;
static bool LED_2_STATUS = false;
Thread blinkLED1Thread = Thread();
Thread blinkLED2Thread = Thread();
Thread servoThread = Thread();
ThreadController master = ThreadController();
void setup() {
pinMode(LED_1_PIN, OUTPUT);
pinMode(LED_2_PIN, OUTPUT);
pinMode(SERVO_PWR_PIN, OUTPUT);
servo.attach(SERVO_SIGNAL_PIN);
blinkLED1Thread.onRun(blinkLED1);
blinkLED1Thread.setInterval(250);
blinkLED2Thread.onRun(blinkLED2);
blinkLED2Thread.setInterval(500);
servoThread.onRun(runServo);
master.add(&blinkLED1Thread);
master.add(&blinkLED2Thread);
master.add(&servoThread);
}
void loop() {
master.run();
}
void runServo() {
// Give the servo a few seconds to reset to the starting position.
servo.write(0);
delay(5000);
while(true) {
for(pos = 0; pos < 180; pos += 1) {
servo.write(pos);
delay(15);
}
for(pos = 180; pos >=1; pos-=1) {
servo.write(pos);
delay(15);
}
}
}
void blinkLED1() {
LED_1_STATUS = !LED_1_STATUS;
digitalWrite(LED_1_PIN, LED_1_STATUS);
}
void blinkLED2() {
LED_2_STATUS = !LED_2_STATUS;
digitalWrite(LED_2_PIN, LED_2_STATUS);
}
</code></pre>
<p>When I flash this to the Due, two disappointing things happen:</p>
<ol>
<li>The LEDs, which previously blinked at the correct rates, now stay lit and do not blink at all; and</li>
<li>The servo doesn't move</li>
</ol>
<p>Now perhaps I have a bum servo, or perhaps I haven't wired it up correctly, but the most concerning thing to me is that the LEDs are no longer blinking. I have a <em>feeling</em> that once I get those blinking again, the servo will <em>probably</em> start sweeping as well.</p>
<p>Can anyone spot <em>anything</em> that jumps out at them as being wrong here, wiring and code alike?</p>
| <p>One thing that immediately jumps out at me is you are trying to power the servo from a digital pin. That is very very wrong.</p>
<p>The servo must be powered from the +5V pin (or +3.3V pin if it's a 3.3V servo) and only the "pulse" pin is connected to an Arduino's PWM capable IO pin.</p>
<p>Also, I don't know how the "Threads" library works, but it looks to me like it's not real threads, but a "round robin" execution of function with time delays. If one of your functions never returns (like your servo one) then the whole system will lock up. You need to make your servo function non-blocking like your LED functions. Give it a 15ms time setting and only move one step of the servo each time it gets called.</p>
<p>Ok, according to comments and research I can confirm that in fact the Thread library is really badly named. It doesn't run threads, it just runs different functions at different times. Those functions MUST be "single shot" - i.e., they MUST complete before anything else can happen. There is absolutely no concurrency whatsoever. It is entirely up to you to ensure that all your "threads" are fairly simple repetitive operations which are to be run at specific points in time.</p>
<p>Basically the operation is thus:</p>
<ul>
<li>Add a function and its time to a list.</li>
<li>Work through the list to find a function whose time has expired</li>
<li>Call that function</li>
<li>Continue through the table</li>
<li>Go back to the beginning</li>
</ul>
<p>If you have two functions both with the same time then one function will be called first and execute to completion, then the other function will be called afterwards, to execute to completion. Only when a function returns is the system able to move on to the next entry in the function list.</p>
<p>You <em>must not</em> use <code>delay()</code> in your "thread" functions for anything more than maybe 1-2ms of delay <em>in total</em>. You <em>MUST</em> return from your thread with enough time for your next timed event to execute, otherwise it will be delayed, or never run at all.</p>
<p>So your servo thread would look something like this:</p>
<ol>
<li>Add my current "direction" to the servo value</li>
<li>If the servo value < 0 or > 180 then invert the direction and limit the value to 0-180.</li>
<li>Write the value to the servo</li>
</ol>
<p>That is then triggered every 15ms by the thread library.</p>
<p>So as real code it may look like:</p>
<pre><code>void runServo() {
static int direction = 1; // 1 = up, -1 is down
static int value = 0;
value += direction;
if ((value <= 0) || (value >= 180)) {
direction = 0 - direction; // Change direction from + to - or - to +
}
value = max(min(180, value), 0); // Clamp it to between 0 and 180
servo.write(value);
}
</code></pre>
|
12600 | |arduino-uno|linux|mac-os| | Same Arduino Sketch when uploaded from a Linux machine does not work | 2015-06-12T20:03:17.030 | <p>I am trying out some code using the Arduino IDE. The code basically tries to connect to a server and push some data to it.</p>
<p>When I upload the sketch to the Arduino from Mac (Apple PC running on Mac OS) the code works as expected without an error.</p>
<p>However, when I upload the same code/sketch from a Linux machine on Ubuntu, the arduino does not operate as expected.</p>
<p>I tried taking a diff comparison of the HEX files created in both machines to check whether there are any differences (expecting very few). But found that there a lot of differences.</p>
<p>What am I missing? Why isn't my code working when uploaded via the Linux PC!!!!!</p>
| <p>Got this sorted.</p>
<p>The issue was that different versions of the library was being used in both the PCs. One we made sure that the Linux PC used the same as the MAC one it all worked fine!!!</p>
<p>Thanks Guys</p>
|
12613 | |serial|library|avr|uart|class| | Custom Arduino library problem | 2015-06-13T13:36:16.967 | <p>I have made my custom serial(UART) library.
So I made uart.h and uart.cpp files as following.</p>
<blockquote>
<p>uart.h</p>
</blockquote>
<pre><code>#ifndef UART_H
#define UART_H
#include <avr/io.h>
#include <stdlib.h>
//creating class named uart
class uart{
public:
// creating constructor
uart(void);
//function to start uart at given baudrate
void start(int baudrate);
// function to read uart input
unsigned char read();
// function to print data on serial monitor
void print(unsigned char data);
// function to print string on serial monitor
void print(char *string);
// function to print data with given base
void print(unsigned char data,unsigned int base);
//function to print data like printf
void print(char* str,unsigned char data);
// function to read data by printing string
unsigned char read(char* string);
};
#endif
</code></pre>
<blockquote>
<p>uart.cpp</p>
</blockquote>
<pre><code>#include "uart.h"
uart::uart(void);
void uart::start(int baudrate){
long BAUDRATE = ((F_CPU)/(baudrate*16UL)-1);
UBRR0H = (BAUDRATE >> 8);
UBRR0L = BAUDRATE;
// enable recieve and transmit
UCSR0B |= 1 << RXEN0 | 1 << TXEN0;
// data size is equal to 8 bits
UCSR0C |= 1 << UCSZ00 | 1 << UCSZ01;
}
unsigned char uart::read(){
//wait until receive complete.
while(!(UCSR0A & (1 << RXC0)));
// return received byte
return UDR0;
}
void uart::print(unsigned char data){
// wait until UDR is empty
while(!(UCSR0A & (1 << UDRE0)));
//place data into UDR
UDR0 = data;
}
void uart::print(unsigned char* string){
int index = 0;
// print string character by character
while(string[index] != '\0'){
print(string[index]);
index++;
}
}
void uart::print(unsigned char data,unsigned int base){
//buffer to store converted data
char buffer[10];
//convert data to ascii
itoa(data,buffer,base);
//print converted data
print(buffer);
}
// function to print data like printf(%d,data);
void uart::print(char* str,unsigned char data){
int index = 0;
// print string character by character
while(str[index] != '\0'){
if(str[index] == '%'){
index++;
if(str[index]=='d') print(data,10);
else if(str[index] == 'b') print(data,2);
else if(str[index] == 'x') print(data,16);
index++;
}
print(str[index]);
index++;
}
}
unsigned char uart::read(unsigned char* string){
// print given string
print(string);
// return read char
return(read());
}
</code></pre>
<blockquote>
<p>test.cpp</p>
</blockquote>
<pre><code>#include "uart.h"
int main(){
uart.start(9600);
uart.print("Hello world\n");
}
</code></pre>
<p>Now all of above function works if i write all function and declations in single <strong>.h</strong> file and don't divide my header file in <strong>.h</strong> and <strong>.cpp</strong> file. if i compile this given program i get following error.</p>
<blockquote>
<p>Error</p>
</blockquote>
<pre><code>src/uart.cpp
src/uart.cpp:3:16: error: declaration of 'uart::uart()' outside of class is not definition [-fpermissive]
uart::uart(void);
^
src/uart.cpp:39:6: error: prototype for 'void uart::print(unsigned char*)' does not match any in class 'uart'
void uart::print(unsigned char* string){
^
In file included from src/uart.cpp:1:0:
src/uart.h:31:7: error: candidates are: void uart::print(char*, unsigned char)
void print(char* str,unsigned char data);
^
src/uart.h:28:7: error: void uart::print(unsigned char, unsigned int)
void print(unsigned char data,unsigned int base);
^
src/uart.h:25:7: error: void uart::print(char*)
void print(char *string);
^
src/uart.cpp:30:6: error: void uart::print(unsigned char)
void uart::print(unsigned char data){
^
src/uart.cpp:91:15: error: prototype for 'unsigned char uart::read(unsigned char*)' does not match any in class 'uart'
unsigned char uart::read(unsigned char* string){
^
In file included from src/uart.cpp:1:0:
src/uart.h:34:16: error: candidates are: unsigned char uart::read(char*)
unsigned char read(char* string);
^
src/uart.cpp:20:15: error: unsigned char uart::read()
unsigned char uart::read(){
^
.build/uno/Makefile:166: recipe for target '.build/uno/src/uart.o' failed
make: *** [.build/uno/src/uart.o] Error 1
Make failed with code 2
</code></pre>
<blockquote>
<p><strong>PS:</strong> I use <code>inotool</code> to compile and upload my programs to arduino and it works great. So you will find <code>src/</code> in error.</p>
</blockquote>
<p>Please help me. I'm stuck here.</p>
| <pre><code>uart::uart(void);
</code></pre>
<p>That's a prototype, not a function. It needs a body. Also, using "void" to say "no parameters" is really confusing. Better to leave it out all together.</p>
<pre><code>uart::uart() {
}
</code></pre>
<hr>
<pre><code>uart.start(9600);
uart.print("Hello world\n");
</code></pre>
<p><code>uart</code> is a class, not an instance. You should be using <code>uart::start(9600)</code> if you first set your functions to be <code>static</code>, or create an instance from the <code>uart</code> class:</p>
<pre><code>uart myUart;
int main() {
myUart.begin(9600);
myUart.print("Hello world\n");
}
</code></pre>
<hr>
<p>Watch your random <code>unsigned</code> entries...</p>
<pre><code>uart.h:
unsigned char read(char* string);
uart.c:
unsigned char uart::read(unsigned char* string){
</code></pre>
<p>... There may be others too.</p>
|
12619 | |arduino-uno| | How to control a large number of devices with an Arduino | 2015-06-13T18:42:07.663 | <p>I'm doing some initial research on a project I have in mind. I am super new to all this Arduino stuff so taking it slow and gathering lots of info.</p>
<p>I want to control around 1000 small linear actuators to push/pull a very small load. The purpose of this question is specifically how to manage that many devices. The devices won't ever need to start their own transmissions so the Arduino can get everything done by polling them ...I hope ...and I don't think it would be a lot of data to each device but I imagine overall it may be. I want to control each device at the "same" time, all with the same cabling distance (around 2m). From what I can tell, a <a href="https://en.wikipedia.org/wiki/CAN_bus" rel="nofollow"><strong>CANbus</strong></a> is exactly what I need, where I can assign a unique ID to each device (node) and then write some code to control the network array.</p>
<p>In summary, is a CANbus the ideal bit of hardware here to work with an Arduino to control in real time such a high number of devices?</p>
<p>Thanks,
Nick.</p>
<p>Edit: Sorry for the vagueness, I'm very new to all this so really just looking for keywords to help scope my project out before asking more complex specific questions. It's difficult to formulate what's in my head to experienced people without sounding like a goose. I'm experienced on the software side, but the hardware i/o is all brand new.</p>
<p>Ultimately, I am wanting to sample a grey scale image/sequence of images and depending on the value sampled in a 0-255 range which is mapped to the extension capabilities of each actuator to extend/contract in that pixel.</p>
<p>Hope that is more helpful. Thanks.</p>
| <p>This is just a suggestion, certainly not the only possible approach.</p>
<p><strong>Step 1</strong>: Get a handful of small linear actuators <em>with a builtin
controller</em>. Some actuators have no controller, and will require one
H-bridge and one analog input each. You do not want these. I have seen
some actuators with built-in controllers that can be driven just like
servos, I would suggest you get some of those. At this point you should
carefully look at costs when choosing the actuators.</p>
<p><strong>Step 2</strong>: Learn how to drive those actuators from an AVR-based
Arduino, like an Arduino Uno, using the Servo library. I believe you can
drive up to 12 actuators with a single Arduino.</p>
<p><strong>Step 3</strong>: Drive them using <em>two</em> Arduinos in a master-slave
configuration. The master would be a beefy Arduino, like a Mega or a
Due. It would send commands to the slave using, say, an I2C bus. After
sending the set points for the actuators, it would send a "go" order to
the I2C broadcast address. The slave would be the Uno. It would
interpret the commands and actually drive the actuators.</p>
<p><strong>Step 3b</strong>: Change the master's program to <em>pretend</em> it is controlling
many slaves, and a total of 1000 actuators. In reality, all the
slaves would have the same I2C address: that of the unique slave
actually available. This will tell you whether your master is powerful
enough for the job, and you will see how the performance scales.</p>
<p><strong>Step 3c</strong>: Optimize the slave's code. Try to have it work with an
8 MHz clock, and use as little flash and RAM as possible.</p>
<p><strong>Step 4</strong>: Replace the slave Arduino with a bare AVR chip. You will
have to learn how to program it via ISP, but the information is widely
available. An Uno is an ATmega328P at heart, but depending on the
program size, you may get away with an ATmega48A, which is the same
thing only with less memory, and dirty cheap. Or even with a still
cheaper ATtiny. If you can make your program work with an 8 MHz
clock, then use the internal oscillator, which will save you having to
buy an external resonator. All this is to keep the costs reasonable.</p>
<p><strong>Step 4b</strong>: Test, test, test. Last chance to change your mind before
committing big bucks.</p>
<p><strong>Step 5</strong>: If everything works at this stage, it's time to scale up.
The same master Arduino, and one bare AVR for each dozen actuators, each
with it's own I2C address.</p>
|
12621 | |arduino-uno| | Determining which section of code uses the most flash | 2015-06-13T22:15:37.683 | <p>I'm running into the 32k flash ceiling of my 328p. The code is pretty compact but I need help making it smaller.</p>
<p>Is there an analysis tool (part of avr?) that can tell me which functions take up the most space? Obviously looking at the source code won't help because I don't know how the compiler decides to reorganize things.</p>
<p>I've moved strings to PROGMEM, but I'm still hitting the ceiling.</p>
<p>What are some tips for space saving?
What are some ways of seeing what's taking up the most space?</p>
| <p>For knowing which functions take the most space, I generally use
<code>avr-nm</code>. This command is intended to display the symbol table of a
compiled program. It is one of the tools that you get when you install
the Arduino environment, so you already have it. avr-nm provides the
same information as <code>avr-objdump -t</code>, but it can display it in a nicer
format.</p>
<p>As an example, I ran the following command on the basic blinky program:</p>
<pre><code>avr-nm --size-sort -Crtd blink.elf
</code></pre>
<p>And this is the output:</p>
<pre><code>00000148 T __vector_16
00000118 T init
00000114 T pinMode
00000108 T digitalWrite
00000082 t turnOffPWM
00000076 T delay
00000070 T micros
00000040 T loop
00000026 T main
00000020 T digital_pin_to_timer_PGM
00000020 T digital_pin_to_port_PGM
00000020 T digital_pin_to_bit_mask_PGM
00000016 T __do_clear_bss
00000010 T port_to_output_PGM
00000010 T port_to_mode_PGM
00000008 T setup
00000004 B timer0_overflow_count
00000004 B timer0_millis
00000001 b timer0_fract
</code></pre>
<p>The first column is the size of the object referenced by the symbol.
Second column is the type, where ‘t’ (upper or lower case) means “text”
(code and PROGMEM data), ‘d’ means “initialized data” (stored in flash
and copied to RAM at startup) and ‘b’ means “uninitialized data” (a.k.a.
“BSS”, occupies no flash, only RAM). The last column is the symbol's
name. In this example you can see that the biggest function is
<code>__vector_16</code> (the ISR for timer 0 overflow), and it takes 148 bytes of
flash.</p>
<p>The options I passed to avr-nm are the following:</p>
<ul>
<li><code>--size-sort</code>, obviously, sorts the symbols by size. It also displays
the size, instead of the address, on the first column.</li>
<li><code>-C</code> is for demangling the C++ symbols. For example, instead of
displaying “_ZN14HardwareSerial5beginEm”, it would display
“HardwareSerial::begin(unsigned long)”.</li>
<li><code>-r</code> means “reverse sort”. This is for having the biggest functions at
the top, instead of at the bottom.</li>
<li><code>-td</code> is for displaying the sizes in decimal instead of hexadecimal.</li>
</ul>
<p>Since you are only interested in flash usage, you can ignore the symbols
in BSS. On a unixish OS, you could just pipe into <code>grep -iv ' b '</code></p>
|
12625 | |flash|float|arduino-mini| | Store floats in and reading them from flash | 2015-06-14T08:46:47.587 | <p>How do I store floats in flash and how do I read them from there? (I need a look-up table for pairs of float values.)</p>
<p>The storing part doesn't seem to be so difficult as this compiles:</p>
<pre><code>PROGMEM float value1 = 1.23456;
</code></pre>
<p>But how do I read them? Do I need to copy them byte by byte to a float variable, or is there a better way? (I am using an Arduino ATmega 328p with 4-byte floats.)</p>
| <p>I realize that the OP asked about a single value, but I thought I'd add info on retrieving from an array.</p>
<pre><code>const float pmdata[] PROGMEM = {1.0, 2.0, 3.0};
</code></pre>
<p>then retrieve thusly:</p>
<pre><code>float val = pgm_read_float(&pmdata[idx]);
</code></pre>
|
12627 | |sensors| | How to use Ultrasonic Sensor's trig pin, and why it is needed? | 2015-06-14T09:20:23.027 | <p>I have HC-SR04 Ultrasonic Sensor with me. I couldn't understand the "Trig" pin's working structure and the working technic. Do we really need it while we use? </p>
<p>(With Arduino examples, I generally use Echo pin more than trig pin.)</p>
<p><img src="https://i.stack.imgur.com/X2dK8.jpg" alt="image"></p>
| <p>I stumbled across your topic while working in a personal project. As people said earlier, your doubts must be related to the different versions of this board.</p>
<p>Keep in mind that, when using the 4-pin you can keep the ECHO full online as an input, while in the 3-pin version, you need to cancel the ECHO to use it as Output for the TRIG.</p>
<p>This is particularly useful when you need to make a environmental analysis to different responses to different actions.</p>
|
12634 | |wifi|arduino-yun|node.js| | Arduino Yun used as Wi-Fi hotspot | 2015-06-14T16:04:44.927 | <p>I use for a project an Arduino Yun with Node.JS + socket.io to provide interactivity between a smartphone, driving through a webpage different devices. </p>
<p>I would like to enable this service for several smartphones at the same time. However I would like to work in the very same conditions that a (well configured) hotspot does:</p>
<ol>
<li>I want to ensure that no user can see the other users on the network,</li>
<li>I want to have a limited number of connections on the Yun at the same time,</li>
<li>I want to force the different users when connected to the Wi-Fi to be routed to a captive portal on the first connection.</li>
</ol>
<p>Does anyone know first if it is possible with an Arduino Yun (maybe some actions must be performed on a NodeJS virtual server as point 2). If yes, do you have a tutorial or any clues (do I have to use LuCi)?</p>
<p>Last question, in the same topic, I would like to use a fast granted access using NFC tag emulation to provide Wi-Fi credentials. Has anyone tried this with Arduino Yun and a shield?</p>
| <p>Finally, here is how I did the job. In short, I separated the two topics of getting a trace of any user using <code>socket.io</code> and giving a limitations of the number of users.</p>
<p>First, my Arduino Yun is on a Ethernet network where a router, acting also as the internet gateway, is a dhcp server. My Arduino Yun have a static IP address in the subnet of this router (so it is not a dhclient). This can be set either by modifying the file <code>/etc/init.d/network</code>.</p>
<p>Including the lines:</p>
<pre><code>config 'interface' 'wan'
option 'proto' 'static'
option 'ifname' 'your_interface_name'
ipaddr xxx.xxx.xxx.xxx
</code></pre>
<p>or by using the LuCi interface.</p>
<p>For more information about the way to properly configure the network in OpenWRT, see <a href="https://wiki.openwrt.org/doc/uci/network" rel="nofollow">Network configuration</a>.</p>
<p>Then the router is set to authorize only few IP addresses. </p>
<p>The last step is to bridge the Wi-Fi and the Ethernet (WAN and LAN) keeping the configuration of the Ethernet interface. This can be done using the LuCi interface. Be careful of what interface configuration you keep. <a href="http://root42.blogspot.fr/2014/01/how-to-setup-openwrt-router-as-wifi.html" rel="nofollow">How to setup an OpenWRT router as a Wi-Fi bridge to an Ethernet router</a> gives the way to do this.</p>
<p>Note that this can also be done using the Arduino Yun as a DHCP server if you don't want to be connected on a network.</p>
<p>In the end, any connections on the Arduino Wi-Fi will get its IP address in the authorized range (up to 16 users at the same time in my case) by the router/DHCP server through the bridge.</p>
<p>In <code>socket.io</code>, I took the id that is given to any connected client and the IP address to ensure that I have a same user.</p>
<p>About the NFC dynamic tag, I developed a NFC specific board with a dynamic tag in the Arduino Yun/Uno format and its library to push through the bridge between ATmega and Atheros any new Wi-Fi code or any webpage. I think it is outside of this scope so if you need anything about this I can give you in PM.</p>
<p>I finally get at the end a device:</p>
<ul>
<li>Connected to an existing network and accessing the internet,</li>
<li>Serving the webpages I want using my node serve,</li>
<li>Able to push any information on any other devices on the network through my nodeJS server,</li>
<li>Enabling access to people to local or network content,</li>
<li>Serving some specific local information through the NFC shield.</li>
</ul>
|
12647 | |sensors| | Multiple LEDs & HC-SR04 | 2015-06-15T03:11:14.620 | <p>I want to use a distance sensor like the HC-SR04 to power a stop light like parking sensor for my garage. I have seen a lot of tutorials on how to use the HC-SR04 to power a single LED and found the schematic below on how to control up to 14 LEDs by hooking them onto the 5v and using a transistor. I have added a box where I would hook the sensor in. My question is, would it work if I had the sensor hooked into the 5v as well. The plan is to have 3 sets of 14 LEDs and have one set on at any given time. I plan on using an Arduino Uno. <img src="https://i.stack.imgur.com/TKtrK.jpg" alt="Schematic"></p>
| <p>If I am understanding correctly, you have 3 LEDs ... call them A, B and C (the fact that they are a group of 14 LEDs is a red herring). As a function of the distance measured, you want ONE of LED A, B or C lit.</p>
<p>Since you are using an Arduino, you have GPIO pins. Connect a different GPIO to each of A, B and C. You can then write an application that senses the distance (as measured by the HC-SR04) and depending on the distance returned, have a set of "if" statements which will choose which of the GPIOs to set HIGH and the others LOW. The GPIO set HIGH will switch on the corresponding LED.</p>
<p>In fact, its going to look a lot like this Instructable:</p>
<p><a href="http://www.instructables.com/id/Simple-Arduino-and-HC-SR04-Example/" rel="nofollow">http://www.instructables.com/id/Simple-Arduino-and-HC-SR04-Example/</a></p>
|
12660 | |arduino-uno|serial|communication| | print data after being plugged back into USB | 2015-06-15T15:50:00.870 | <p>I have an arduino uno powered by a battery on a buggy with a sonar distance sensor. I have a program that calculates the speed it's going, and I want to correlate speed with stopping distance. I can measure the stopping distance manually, but I want the arduino to report to me the speed it was going when the motor was turned off. I don't have an LCD display - I wanted to print the number to the serial monitor, but plugging it back into the USB port resets everything I think, or at least the serial monitor.</p>
<p>Without buying more components, can I get the data (calculated speed) somehow?</p>
| <p>You could have it write the final speed to EEPROM after the motor is shut-off, and output this value when the Arduino boots, see:
<a href="http://www.arduino.cc/en/Reference/EEPROM" rel="nofollow">http://www.arduino.cc/en/Reference/EEPROM</a></p>
|
12664 | |button| | How to avoid that my arduino clicks eternally? | 2015-06-15T17:06:49.733 | <p>I have accidentally implemented a program that imitates the click of the mouse.</p>
<p>The problem is that now I can´t delete the program because each time that I connect the USB, the computer starts clicking everything and it is not possible to upload a new program.</p>
<p>Can I solve this problem?</p>
| <p>Hold the RESET button as you plug the Arduino in and keep it pressed all the time it's plugged into your computer. Load Blink.ino into the IDE and compile it. Press the UPLOAD button in the IDE and move the mouse to somewhere "safe". Release the RESET button.</p>
<p>Do those last three steps in rapid succession and you should be fine.</p>
|
12666 | |arduino-uno|programming| | Arduino UNO button LED brightness vary | 2015-06-15T18:55:48.623 | <p>I am using an Arduino UNO and I am trying to vary the brightness by steps by 0.5 volts till it gets to a max of 5.0 V using buttonA and decrease the brightness of the LED by 0.5 volts with buttonB. The Problem I have is that when I push buttonA the LED steps it's voltage by 0.5V all the way to 5.0V and with buttonB its steps down to 0. I would like to have the LED step each time I press the button not all at once. Here is my code that I have so far can someone help me with telling the Arduino to Step each time a button is pressed. CODE IS DIFFERENT from another post I did </p>
<p>HERE is my code:</p>
<pre><code>int ledPin = 9; // must be a PWM digital pin
int buttonApin = A2; //buttonA to analog 2
int buttonBpin = A1; // buttonB to analog 1
int maxBright = 255; // between 0 and 255
int ms = 1500; // delay in milliseconds
int buttonPushCounterA = 0; //counter for the number of button presses
int buttonStateA = 0; // current state of the button
int lastButtonStateA = 0; // previous state of the button
int buttonPushCounterB = 0; //counter for the number of button presses
int buttonStateB = 0; // current state of the button
int lastButtonStateB = 0; // previous state of the button
void setup()
{
pinMode(ledPin, OUTPUT);
pinMode(buttonApin, INPUT_PULLUP);
pinMode(buttonBpin, INPUT_PULLUP);
}
void loop()
{
if (digitalRead(buttonApin) == LOW) //if buttonA is pushed
{
buttonStateA = digitalRead(buttonApin);
if (buttonStateA != lastButtonStateA)
{
if(buttonStateA == LOW)
{
buttonPushCounterA++;
}
}
// fade from min to max in increments of 25.5 points: basically (0.5 volts)
for (float n = 0; n <= maxBright; n +=25.5)
{
// sets the value (range from 0 to 255):
analogWrite(ledPin,n);
delay(ms);
}
}
if (digitalRead(buttonBpin) == LOW) //if buttonB is pushed
{
buttonStateB = digitalRead(buttonBpin);
if (buttonStateB != lastButtonStateB)
{
if(buttonStateB == LOW)
{
buttonPushCounterB--;
}
}
// fade from max to min in increments of 25.5 points: basically (0.5 volts)
for (float n = maxBright; n >= 0; n -= 25.5)
{
// sets the value (range from 0 to 255):
analogWrite(ledPin, n);
delay(ms);
}
}
lastButtonStateA = buttonStateA;
lastButtonStateB = buttonStateB;
}
</code></pre>
| <p>One problem in your original code is that you are only storing the current state of the buttons if they are pressed. The next problem is that you are looping through all your brightness values when a button is pressed giving you your "fades all the way up in one go" problem.</p>
<p>This would be my replacement for your loop() code:</p>
<pre><code>loop()
{
int currentButtonStateA = digitalRead(buttonApin);
if (currentButtonStateA != lastButtonStateA && currentButtonStateA == LOW)
{
currentBrightness += BRIGHTNESS_INCREMENT; // BRIGHTNESS_INCREMENT is defined at the top of the file with #define BRIGHTNESS_INCREMENT 25
if (currentBrightness > MAX_BRIGHTNESS) // MAX_BRIGHTNESS is defined at the top of the file with #define MAX_BRIGHTNESS 255
{
currentBrightness = MAX_BRIGHTNESS;
}
}
lastButtonStateA = currentButtonStateA;
int currentButtonStateB = digitalRead(buttonBpin);
if (currentButtonStateB != lastButtonStateB && currentButtonStateB == LOW)
{
currentBrightness -= BRIGHTNESS_INCREMENT;
if (currentBrightness < MIN_BRIGHTNESS) // MIN_BRIGHTNESS is defined at the top of the file with #define MAX_BRIGHTNESS 0
{
currentBrightness = MIN_BRIGHTNESS;
}
}
lastButtonStateB = currentButtonStateB;
analogWrite(ledPin, currentBrightness);
}
</code></pre>
<p>Hopefully this is pretty self explanatory. The current button A state is read and stored in a local variable. If it is different to the previous state and it is low, the current brightness is incremented and capped at a maximum value. Next the current button state is stored as the previous state ready for the next run through the loop.</p>
<p>Similar actions are performed for the B button, but with a decrement rather than an increment. Finally the LED brightness is set regardless of whether any buttons have been pressed.</p>
<p>You do not need to store your current button states (buttonStateA) or your counts for the number of button presses (buttonPushCounterA - which you never referenced anyway) or your ms value so could get rid of those global variables. You need a new global variable at the top of your file for currentBrightness (int currentBrightness = 0;).</p>
<p>You have used variables to store various non-changing numeric values, such as "maxBright = 255;" which is good practise, but is better (particularly with Arduino development) to use #define macros instead, such as "#define MAX_BRIGHTNESS 255".</p>
<p>The reason for this is that variables take up memory when the code is running - something that an Arduino Uno doesn't have a lot of, whereas a #define takes up no memory - the compiler uses it as a "search and replace" before compiling your code.</p>
|
12670 | |ethernet|networking| | SFML Packet and Arduino | 2015-06-15T20:12:34.247 | <p>Can the <a href="http://www.sfml-dev.org/documentation/2.3/classsf_1_1Packet.php" rel="nofollow"><code>sf::Packet</code></a> class of SFML-network be ported over to arduino for use with the Ethernet library or would it be too big? I'm working on a client-program where an arduino is a server and a regular computer is the client making a request. I'm using the SFML-network library to make networking easier on myself and would prefer to use the built in features of SFML to make networking easier. If it is not feasible would I be better off using fixed width data to communicate with the arduino</p>
| <p>Without knowing how it all works, my guess is that you would have to port the whole of SFML, which would be <strong>HUGE</strong>. So, "No!" is the answer.</p>
<p>You could, of course, write a library of your own that had an SFML-like interface, but the Arduino networking libraries are already pretty simplistic and easy to use, so what's the point?</p>
|
12674 | |lcd| | LiquidCrystal_i2c and Pin 2 | 2015-06-15T22:15:53.517 | <p>I'm trying to read temperature and humidity from a DHT11 sensor and write values to a 20x4 LCD.
I hit a behaviour I don't understand. When I use the DHT tester program that come with the DHT library, everything works well. I get the DHT information on the Serial console. This DHT tester program use the pin 2 to read the data from the DHT.</p>
<p>I wrote the following code who works perfectly:</p>
<pre><code>#include <Wire.h>
#include <LiquidCrystal_I2C.h> // F Malpartida's NewLiquidCrystal library
#include <DHT.h>
#define DHTTYPE DHT11
#define DHTPIN 13 // Digital
DHT dht(DHTPIN, DHTTYPE);
LiquidCrystal_I2C lcd(0x27, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE);
void setup() {
Serial.begin(9600);
while (!Serial) {
}
Serial.println("Serial OK!");
dht.begin();
lcd.begin(20,4);
lcd.setBacklight(0);
lcd.clear();
lcd.print("Hello! ");
Serial.println("Init finished!");
}
void loop() {
delay(2000);
float DHT_hum = dht.readHumidity();
float DHT_temp_c = dht.readTemperature(false);
float DHT_temp_f = dht.readTemperature(true);
if (isnan(DHT_hum) || isnan(DHT_temp_c) || isnan(DHT_temp_f)) {
Serial.println("Failed to read from DHT sensor!!");
lcd.clear();
lcd.print("fail! ");
return;
}
float heat_index = dht.computeHeatIndex(DHT_temp_f, DHT_hum);
Serial.print("Humidity: ");
Serial.print(DHT_hum);
Serial.print(" %\t");
Serial.print("Temperature: ");
Serial.print(DHT_temp_c);
Serial.print(" *C ");
Serial.print(DHT_temp_f);
Serial.print(" *F\t");
Serial.print("Heat index: ");
Serial.print(heat_index);
Serial.println(" *F");
lcd.clear();
lcd.print("Humi: ");
lcd.print(DHT_hum);
lcd.print("%");
lcd.setCursor(0, 1);
lcd.print("Temp: ");
lcd.print(DHT_temp_c);
lcd.print("C");
lcd.setCursor(14, 0);
lcd.print("HI: ");
lcd.setCursor(14, 1);
lcd.print(dht.convertFtoC(heat_index));
lcd.print("C");
}
</code></pre>
<p>As you can see, I use pin 13 for the DHT11 (DHTPIN).
If I set to it to "2" then my program is no longer working (having the pin connected or not doesn't change the result).
The serial display</p>
<pre><code>Serial OK!
Init finished!
Failed to read from DHT sensor!!
</code></pre>
<p>and that's all, it even doesn't loop to display "Failed to read from DHT sensor!!" again. LCD text doesn't change too. Like if the program is totally exiting after "Serial.println("Failed to read from DHT sensor!!");"</p>
<p>I'm lost... The LCD lib I use is the very common one from fm
<a href="https://bitbucket.org/fmalpartida/new-liquidcrystal/wiki/Home" rel="nofollow">https://bitbucket.org/fmalpartida/new-liquidcrystal/wiki/Home</a></p>
| <p>I'm self answering..
On my Arduino Leonardo, the SDA and SCL pin used for the I2C connexion to the LCD panel, are the same pin than the Digital pin 2 and 3. So using SDA/SCL remove ability to use pin 2 & 3.</p>
|
12683 | |serial|arduino-yun|sketch|python| | Transmitting sketches to Yun with Autobahn - a byte at a time? | 2015-06-16T10:07:57.380 | <p>I am using <a href="https://github.com/tavendo/AutobahnPython/tree/master/examples/twisted/wamp/app/serial2ws" rel="nofollow">this tutorial</a> to connect an Arduino Yun with a browser using Autobahn.</p>
<p>In the python file in the above repo, there is this code:</p>
<pre><code>def controlLed(self, turnOn):
if turnOn:
payload = b'1'
else:
payload = b'0'
self.transport.write(payload)
</code></pre>
<p>Here's the thing - I need to send whole sketches to my Yun, not just '1' or '0'. I tried sending more to the payload (like <code>payload = b'this is part or all of a sketch'</code>) but that doesn't work. I experimented with some other data types but at the moment these are shots in the dark.</p>
<p>How can I send some proper data (like 100 lines of Arduino sketch) with this mechanism? The end goal is that my existing sketch receives the new sketch commands via serial and runs them.</p>
<pre><code>if (port->available()) {
int commands = port->read();
// Run commands here
}
</code></pre>
<p>I would be hugely appreciative of any help. Thank you!</p>
| <p>Partial answer: to send more information than just a single byte, it is possible to run:</p>
<pre><code># python
payload = "Here is a longer string"
# arduino
String commands = port->readString(); // Reads the whole thing
String commands = port->readStringUntil('\n'); // Reads until the given separator
</code></pre>
|
12692 | |arduino-uno|programming|hardware| | How to start Arduino programming? | 2015-06-16T14:49:52.017 | <p>I am totally new to and don't know where to start, I am interested in building new system with combination of hardware and software and every time I search how to make that embedded system it finally reaches to Arduino and don't know anything about that what to buy and I also have some more question like</p>
<ol>
<li>Is one Arduino device required for each Arduino project ?</li>
<li>Should I have to buy more then one device for each project ?</li>
<li>If not then how I will make that project run without Arduino ?</li>
</ol>
| <p>An Arduino is basically a Microcontroller on a handy PCB with built-in programming interface. It also has a simple programming environment to get you up and running quickly.</p>
<p>The chip on the board can be thought of as the "brain" of the system. It's what you program and it's where you upload your software to.</p>
<blockquote>
<p>Is one Arduino device required for each Arduino project?</p>
</blockquote>
<p>Yes and no. You can't "remove" your Arduino from your project and expect it to still work - it'd be like beheading someone - they cease to function without their brain. However you can replicate the Arduino in your system fairly easily so you don't have to embed the whole Arduino into it. You can get a blank chip the same as is on the Arduino reasonably cheaply and program the bootloader (the serial interface for programming it) into the chip using your existing Arduino, then build a new circuit around it. More information here: </p>
<ul>
<li><a href="http://www.arduino.cc/en/Main/Standalone" rel="nofollow">http://www.arduino.cc/en/Main/Standalone</a></li>
</ul>
<blockquote>
<p>Should I have to buy more then one device for each project?</p>
</blockquote>
<p>That depends if your project is complex enough to warrant more than one "brain". Using the "standalone" instructions above you could make multiple chips from one Arduino and embed them all in your one project. </p>
<blockquote>
<p>If not then how I will make that project run without Arduino?</p>
</blockquote>
<p>There are other Arduino boards available that are designed to be embedded in your project. These are much smaller than the "development" boards like the Uno etc. They are also cheaper, being typically the absolute bare minimum you need to get you going. These can be a great way of saving time compared to the Standalone system above, and at the same time saving money compared to using the full blown Arduino boards. Boards include the Mini and Nano range of boards.</p>
<ul>
<li><a href="http://www.arduino.cc/en/Main/ArduinoBoardMini" rel="nofollow">http://www.arduino.cc/en/Main/ArduinoBoardMini</a> </li>
<li><a href="http://www.arduino.cc/en/Main/ArduinoBoardNano" rel="nofollow">http://www.arduino.cc/en/Main/ArduinoBoardNano</a></li>
</ul>
|
12693 | |xbee| | Determine XBee Packet Route | 2015-06-16T14:57:33.457 | <p>I am trying to build a ZigBee network using XBee Pro S2 devices (API Mode).
Setting up the network and sending packets is easy enough.</p>
<p>Is it possible to trace the route a packet travelled from the end-device to the coordinator? </p>
<p>Example:
<br/>I have 2 routers, one in area A connected to the coordinator, and the other in area B connected to the router in area A. End-device enters area B, and transmits a packet to the coordinator. <br><strong>Path: end-device->routerB->routerA->Coordinator</strong>.
<br/>Is it possible to know the end-device is in area B as it is the first router device the packet travelled through? </p>
| <p>It is done by using <a href="https://www.digi.com/wiki/developer/index.php/Large_ZigBee_Networks_and_Source_Routing" rel="nofollow">Source Routing</a></p>
<p>The 16-bit addresses of the hopped devices are added to the RF payload space, thus it will reduce the number of bytes that can be sent in one RF packet.</p>
|
12699 | |serial| | Arduino processing serial comunication - losing data? | 2015-06-16T20:23:21.243 | <p>I'm trying to send an array back and forth between Processing and an Arduino UNO. But I think data is being lost along the way. I simply iterate over the array in Processing and send the Values separately. A new set of data is indicated by the character <code><</code>. On the Arduino the data gets added to a string and sent back for testing. When I print out the string in processing, some data changed to <code>-1</code>.</p>
<p>The array contains <code>{1,2,3,4,5,6,7,8}</code></p>
<p>The Output looks like this:</p>
<pre><code>12345678
12345678
1234-1-1-1-1
12345678
12345-1-1-1
</code></pre>
<p>Is there something I'm missing in terms of implementation, or is this simply a hardware related problem (like slightly different clock speeds)? Is there any way to improve this?</p>
<p><strong>Arduino Sketch:</strong></p>
<pre><code>int srr[8];
int content; // Data received from the serial port
void setup() {
Serial.begin(9600); // Start serial communication at 9600 bps
}
void loop() {
String str = "val:";
int test;
if (Serial.available()){ // If data is available to read,
content = Serial.read();
}
if (content == 60){
for(int i=0; i<=7; i++)
{
str+=Serial.read();
}
Serial.println(str);
}
}
</code></pre>
<p><strong>Processing</strong></p>
<pre><code>Serial myPort; // Create object from Serial class
int arr[]={1,2,3,4,5,6,7,8}; //The array to send
String str;
void setup()
{
size(200,200); //make our canvas 200 x 200 pixels big
String portName = Serial.list()[0];
myPort = new Serial(this, portName, 9600);
}
void draw() {
//write
myPort.write("<");
for (int i =0; i<=7;i++){
myPort.write(arr[i]);
}
//read
if ( myPort.available() > 0){ // If data is available,
str = myPort.readStringUntil('\n'); // read it and store it in val
println(str); //print it out in the console
}
</code></pre>
<p>}</p>
| <p>Ok, let's look at your Arduino program a bit at a time (for that is where the problem lies).</p>
<pre><code>if (Serial.available()) { // If data is available to read,
content = Serial.read();
}
</code></pre>
<p>If there is at least one character available in the buffer then read one character into the variable <em>content</em>.</p>
<pre><code>if (content == 60) {
</code></pre>
<p>If the variable content is <em>60</em> (better to use '>' so you can see what it is), then ...</p>
<pre><code> for(int i=0; i<=7; i++) {
str+=Serial.read();
}
</code></pre>
<p>... read 8 characters from the serial buffer <em>whether there are any characters in there or not</em>.</p>
<p>That last bit is the crunch point. You have an unknown number of characters in the buffer. You had at least one, and that one you read into <em>content</em>. You don't then check to see if there are the required 8 more characters available (or wait in each iteration of the loop for each character to actually arrive) before trying to read that character in.</p>
<p>If you take a moment to read the <a href="http://www.arduino.cc/en/Serial/Read" rel="nofollow">documentation on Serial Read</a> you will see this:</p>
<blockquote>
<p><strong>Returns</strong></p>
<p>the first byte of incoming serial data available <em>(or -1 if no data is available)</em> - int </p>
</blockquote>
<p>The simplest fix is just to make your loop <em>blocking</em> so it waits for a character to arrive before reading it:</p>
<pre><code>for(int i=0; i<=7; i++) {
while (!Serial.available()); // Wait for a character to arrive
str+=Serial.read(); // Read it
}
</code></pre>
|
12703 | |arduino-yun|sketch| | Convert a Serial string to a sketch command on Yun? | 2015-06-16T23:47:27.163 | <p>How can I convert a string like the following:</p>
<pre><code>"pinMode(2, INPUT_PULLUP)"
or
'Keyboard.print("Hello world")'
</code></pre>
<p>into actual code that the Arduino can act on?</p>
| <p>You might also try the Firmata library, too.
It provides similar functionality, and there are some libs for the computer side of it, if you are so inclined.</p>
|
12718 | |arduino-uno|pwm| | Increase PWM bit resolution | 2015-06-17T16:10:10.613 | <p>I would like to increase the PWM bit resolution of the Arduino Uno.
At this moment it is 8-bit which I consider too low.
Is this possible without losing the ability of interrupts and delays?</p>
<p>Koen</p>
<p>EDIT
This setup delivers a 16-bit resultion</p>
<pre><code>void setupPWM16() {
DDRB |= _BV(PB1) | _BV(PB2); /* set pins as outputs */
TCCR1A = _BV(COM1A1) | _BV(COM1B1) /* non-inverting PWM */
| _BV(WGM11); /* mode 14: fast PWM, TOP=ICR1 */
TCCR1B = _BV(WGM13) | _BV(WGM12)
| _BV(CS11); /* prescaler: clock / 8 */
ICR1 = 0xffff; /* TOP counter value (freeing OCR1A*/
}
/* Comments about the setup
Changing ICR1 will effect the amount of bits of resolution.
ICR1 = 0xffff; (65535) 16-bit resolution
ICR1 = 0x7FFF; (32767) 15-bit resolution
ICR1 = 0x3FFF; (16383) 14-bit resolution etc....
Changing the prescaler will effect the frequency of the PWM signal.
Frequency[Hz}=CPU/(ICR1+1) where in this case CPU=16 MHz
16-bit PWM will be>>> (16000000/8)/(65535+1)=30.5175Hz
*/
/* 16-bit version of analogWrite(). Works only on pins 9 and 10. */
void analogWrite16(uint8_t pin, uint16_t val)
{
switch (pin) {
case 9: OCR1A = val; break;
case 10: OCR1B = val; break;
}
}
</code></pre>
| <p>With some calibration you could sum the outputs of two PWM channels with differing weighting resistors. At the extreme you could notionally use one output to provide 8 bits of resolution and scale the other to 1/256th the level and add them so the 2nd channel covers one bit of range and you (again notionally) get 16 bits of resolution. Without immense care and adjustment all you'd get would be a mess.<br>
However by dividing the 2nd channel by 16 or 32 you could add several extra bits of PWM resolution. Just by adding 2 PWM channels analog filtered outputs you add an extra bit (as potential range is doubled for unchanged mV/bit).<br>
Notionally (again) for every additional divide by 2 you get an extra bit of resolution, but this can only be carried out for maybe 4 or 5 or 6 extra bits, with increasing accuracy requirements of scaling resistors and more difficult calibration and proneness to errors. </p>
<p>Brief example.<br>
If one PWM is scaled down to give say 0 - 255 mV in 1 mV step, then summing two PWMs with equal amplitude would give a 0 - 510 mV range in 1 mV steps.<br>
If one PWM is scaled down by a factor of 32 then instead of adding 255 mV to the initial PWMs range it would add only 8 mV to the top end (0.256.32 = 8 mV, but resolution would be in 0.03125 (1/32nd) mV steps. </p>
<p>While this could perhaps be achieved purely with resistor summing and RC filtering, use of an op amp summer would greatly improve results.</p>
<p>Also PWM ripple could be filtered with a simple RC filter but use of one opamp as a buffer (or even just a single transistor as an emitter follower) would give you 3 or 5 poles of low pass filtering and much better chance of achieving extra PWM resolution. I have not inspected the "phase coherence" of the PWM outputs but expect that they move in relative lockstep so you don't get the smoothing advantage of adding two uncorrelated waveforms.</p>
<p>More comment can be made if needed. Ask if interested. </p>
|
12723 | |arduino-due| | How to slow ADC clock speed to 1MHz on Arduino Due? | 2015-06-17T20:43:30.890 | <p>I know that the ADC on the Arduino Due has a clock speed from 1 MHz to 20 MHz. I have two questions: 1. What is the default clock speed when I run a sketch, and 2. How can I change it? (I am using Arduino 1.6.4.)</p>
<p>The reason why I want to slow down the ADC as much as possible is to obtain the maximum source impedance. Is this logic correct? (i.e., if I slow down the ADC in the arduino code to kHz values, then the source impedance will reach MΩ values?)
<img src="https://i.stack.imgur.com/b08cX.png" alt="enter image description here"></p>
| <p>The atod clock is set in the mode register. The clock is 42MHz/(PRESCAL#+1). One way of setting it is the use ADC->ADCMR = ADC_MR_PRESCAL(PRESCAL#), where PRESCAL# is some integer. These symbols are defined in component_adc.h in the Arduino source code.
In the AVR data sheet, the recommended clock is MIN=1MHz, MAX=20 MHZ, corresponding to numbers between 41 and 1. Look in the data sheet, section 43.</p>
|
12725 | |arduino-uno|frequency| | Relationship between baud rate and the frequency of vibration read using ADXL | 2015-06-17T22:08:03.053 | <p>I am doing a project using Arduino Uno and ADXL 345.
I am quite new to this and I came across this post in the link" : <a href="https://www.sparkfun.com/tutorials/240" rel="nofollow">https://www.sparkfun.com/tutorials/240</a>. Here, a user had posted the below question in the forum.</p>
<p>"Im trying to use this accelerometer to test various frequencies of vibration on a cantilevered beam and I wanted to know what the maximum vibration frequency I could find with using this accelerometer, connected to a 16MHz processor, connected to my laptop. I’m mainly a mechanical person, but after doing some research I found the following: Accelerometer has a maximum of 3200Hz output data rate (so maximum frequency would be 1600Hz) Processor can execute 16,000,000 instructions/sec so this probably is okay Communication rate is 9600 bits/sec so in the program above we read at a minimum 6 bytes for each axis, so that’s 24 bits, leaving you able to read 9600/24 = 400 reads/sec resulting in a one to be capable of reading vibrations at 200Hz. If I bump up the baud rate to 115200, I should be able to then read 4800 times a second, thus measuring 2400Hz vibrations?"</p>
<p>But I do not see any replies to this question. I feel the above analysis mostly makes sense. It would be helpful if someone could confirm that the above analysis is right. If not right , then why isn't it right?</p>
<p>Thanks</p>
| <p>Firstly, the datasheet for the accelerometer suggests using >=2Mhz SPI communication rate with 3200 or 1600 Hz output data rate operation.</p>
<p>Since the Arduino SPI library default clock is 4Mhz, the Arduino can handle 3200 Hz sampling, so the maximum frequency you could distinguish would be 1600 Hz.</p>
<p>So the Arduino and accelerometer can detect vibrations up to 1600Hz.</p>
<p>Next, you send the data to your laptop. At 9600 BAUD, you are correct in saying that since the data is 24 bits, it will only update your laptop with the Arduino's measured frequency at 9600/24 = 400 Hz. So 400 times a second the Arduino could tell the laptop what frequency it measures, the measurement having a maximum frequency of 1600 Hz.</p>
<p>For the Arduino to simply pass the raw data to the laptop at 3200 Hz, you would need 24 bits * 3200 Hz = 76800 BAUD minimum.</p>
<p>The measurement data is in any case limited by the accelerometer sampling rate of 3200Hz.</p>
|
12732 | |programming|arduino-mega|analogread|sound|analog-sampling| | Can do I make an Arduino program that can decipher telephone touch tones? | 2015-06-18T01:44:54.177 | <p>I have an old land line phone that I want to connect to my Arduino. Then I would like to write a program that can decipher the touch-tone button presses (which are a combination of two tones) so that the Arduino can react to specific key presses and numeric sequences. My final goal is to make the Arduino play specific messages when the user enters in codes. I am really not sure even where to begin. </p>
<p>Thanks for the hardwares fixes for this problem, but if possible, I am looking for a softwares solution.</p>
<p>This will be used to make a telephone (with an attached Arduino) that will play a series of conversations when specific codes are dialed.</p>
| <p>As John Taylor said, DTMF is not a single tone but two tones transmitted simultaneously, which select the digit from a two-dimensional grid. (<em>Dual</em> tone multi-frequency). This allow 16 possible combinations from only 8 distinct tones.</p>
<p>There are chips available specifically for the task of decoding DTMF, but it's always nice to try and find a one-chip solution.</p>
<p>There are two solutions that I can think of:</p>
<ul>
<li><a href="http://wiki.openmusiclabs.com/wiki/ArduinoFFT" rel="nofollow">ArduinoFFT</a> - a <strong>Fourier transform</strong> is an operation that splits a time-based signal into its frequency components. If you control the ADC directly instead of via the Arduino library, it is easily fast enough to sample a DTMF signal. Once you've done the FFT you just need to find the peaks in the output, which will tell you the tones that are present.</li>
<li>If you put the signal through the analog comparator and <strong>count the rate of zero-crossings</strong> (use an interrupt with a routine that increments a number, you may miss some if you just poll the pin), the rate of crossings should be <strong>unique for each tone combination</strong>. Counting for e.g. 10 ms and looking up the closest match from a table you've pre-measured should give reliable decoding, and is a slightly less brute-force approach than an FFT.</li>
</ul>
<p>That said, you won't be able to beat a dedicated chip (although I personally think this way is much more fun.)</p>
<p>Happy hacking!</p>
|
12740 | |serial|programming|pins|ftdi| | Find number of RX and TX-pin on ArduiMu | 2015-06-18T03:12:01.027 | <p>I've got an <a href="https://store.3drobotics.com/products/arduimu-v3" rel="nofollow noreferrer">Arduino V3+</a> and need to find the correct PIN number for its RX and TX-pin on the FTDI-connector.</p>
<p>How can I find out the correct number of them to use them with the SoftwareSerial-library?</p>
<p><strong>Why I need these numbers:</strong></p>
<p>I'm connecting a Sparkfun Bluetooth Mate/BlueSMIRF to the ArduiMUs FTDI headers and need to set a few settings in its command mode before it operates without flaws.
This is the code I'm using:</p>
<pre><code>#include <SoftwareSerial.h>
int bluetoothTx = ???; // TX-O pin of bluetooth mate, Arduino D2
int bluetoothRx = ???; // RX-I pin of bluetooth mate, Arduino D3
SoftwareSerial bluetooth(bluetoothTx, bluetoothRx);
void setup()
{
Serial.begin(9600); // Begin the serial monitor at 9600bps
bluetooth.begin(115200); // The Bluetooth Mate defaults to 115200bps
bluetooth.print("$$$"); // Enter command mode
delay(5000); // Short delay, wait for the Mate to send back CMD
bluetooth.println("U,9600,N"); // Temporarily Change the baudrate to 9600, no parity
// 115200 can be too fast at times for NewSoftSerial to relay the data reliably
bluetooth.begin(9600); // Start bluetooth serial at 9600
}
</code></pre>
<p><img src="https://i.stack.imgur.com/ySSNf.png" alt="enter image description here"></p>
| <p>You can use FTDI cable with your board on the last row of pads as you have highlighted.</p>
<p>Unfortunately your board designers do not publish a pdf version of the schematic so I opened the provided schematics in EAGLE and exported the FTDI connector diagram.</p>
<p>Here is the FTDI connector connections from the schematic:</p>
<p><img src="https://i.stack.imgur.com/8WX32.png" alt="FTDI"></p>
<p>Here is the pinout of the FTDI cable</p>
<p><img src="https://i.stack.imgur.com/rdsaD.png" alt="FTDI Cable"></p>
<p>So you can solder a 6 pin header on the bottom row and use the standard FTDI cable.</p>
<p>The FTDI row on your board indicates "BLK" on the left so orient your FTDI connector's black wire with the "BLK" pad on your board.</p>
<p><strong>EDIT:</strong></p>
<p>As per your edits you are using hardware serial on your arduino board to monitor and you are using one instance of "SoftwareSerial" to interface with bluetooth.</p>
<p>As <a href="http://www.arduino.cc/en/Reference/SoftwareSerial" rel="nofollow noreferrer">SoftwareSerial</a> library says, you can define any digital pins for Tx and Rx. In the example they have used Arduino pins 10 (pin 14 of the ATMEGA) and 11 (pin 15 of ATMEGA) for Rx and Tx respectively. In your non-standard arduino board, the micro-controller pin 14 is labeled as PWM1 and pin 15 is labeled as MOSI and they are brought out on connector JP7.</p>
<p><img src="https://i.stack.imgur.com/fitkg.png" alt="port"></p>
<p>So in a nutshell you can use pin 4 of JP7 as SoftRx and pin 5 of JP7 as SoftTx.</p>
<p>If those pins are in use, you can always use other digital pins that are unused in your design. Just refer to the schematic of your board, ATMEGA328 datasheet and arduino libraries.</p>
|
12763 | |programming| | Weird Arduino math result | 2015-06-19T03:51:32.840 | <p>I have a simple code, part of which contains the calculation 800/1000, which seems to return a value of zero for some reason (even though I store it in a float variable). When I replace the calculation with the expected result (0.8) the code works as expected, I just wonder why the calculation doesn't produce the same result. </p>
| <p>Both 800.0/1000 or ((float)800)/1000 will work.</p>
<p>The former works only with hardcoded constants, while the latter works also with variables:</p>
<pre><code>int a = 800;
int b = 1000;
float c = ((float)a) / b;
</code></pre>
|
12770 | |arduino-uno|sensors| | How to Store the results from a Ping Sensor in a variable | 2015-06-19T13:17:12.420 | <p>I need your suggestions and help with my Ping Sensor.
I have an Arduino Uno with a Parallax Ping sensor and a motor.</p>
<p>My ping sensor is set to to start the motor when the nearest object is <= 10cm. That works fine.
Now, I'd like the motor to start only if the values of the sensor are progressing in a decreasing manner i.e 15, 14, 13, 12, 11, 10 but do nothing if the values are progressing in a increasing manner.</p>
<p>I was thinking if I stored the last 3 pings as variables and using an if/else statement but I don't know how to implement it.</p>
<p>How can I implement this, or if you have any other suggestion, please help me.
Thank you</p>
<p>Here is what i have so far:</p>
<pre><code>/* Ping))) Sensor
This sketch reads a PING))) ultrasonic rangefinder and returns the
distance to the closest object in range. To do this, it sends a pulse
to the sensor to initiate a reading, then listens for a pulse
to return. The length of the returning pulse is proportional to
the distance of the object from the sensor.
The circuit:
* +V connection of the PING))) attached to +5V
* GND connection of the PING))) attached to ground
* SIG connection of the PING))) attached to digital pin 7
http://www.arduino.cc/en/Tutorial/Ping
created 3 Nov 2008
by David A. Mellis
modified 30 Aug 2011
by Tom Igoe
This example code is in the public domain.
*/
// this constant won't change. It's the pin number
// of the sensor's output:
const int pingPin = 7;
const int motorPin = 9;
//Yomis code
//int pings[3] = {-1,-1,-1};
//int i;
//bool Increasing(int p1, int p2, int p3)
//{
// if(p1 < p2 && p2 < p3){
// return true;
// }
//}
//
//bool Decreasing(int p1, int p2, int p3)
//{
// if(p1 > p2 && p2 > p3){
// return true;
// }
//}
//
//end of yomis code
void setup() {
// Set up the motor pin to be an output:
pinMode(motorPin, OUTPUT);
// initialize serial communication:
Serial.begin(9600);
}
void loop()
{
// establish variables for duration of the ping,
// and the distance result in inches and centimeters:
long duration, inches, cm;
// The PING))) is triggered by a HIGH pulse of 2 or more microseconds.
// Give a short LOW pulse beforehand to ensure a clean HIGH pulse:
pinMode(pingPin, OUTPUT);
digitalWrite(pingPin, LOW);
delayMicroseconds(1000);
digitalWrite(pingPin, HIGH);
delayMicroseconds(2000);
digitalWrite(pingPin, LOW);
// The same pin is used to read the signal from the PING))): a HIGH
// pulse whose duration is the time (in microseconds) from the sending
// of the ping to the reception of its echo off of an object.
pinMode(pingPin, INPUT);
duration = pulseIn(pingPin, HIGH);
// convert the time into a distance
inches = microsecondsToInches(duration);
cm = microsecondsToCentimeters(duration);
Serial.print(inches);
Serial.print("in, ");
Serial.print(cm);
Serial.print("cm");
Serial.println();
delay(1000);
// //Yomis code
// if (cm <= 10)
// {
// Serial.println();
// Serial.println(pings[0]);
// Serial.println(pings[1]);
// Serial.println(pings[2]);
// Serial.println();
// if(Increasing(pings[0],pings[1],pings[2]))
// {
// int Speed1 = 100; // between 0 (stopped) and 255 (full speed)
// int Time1 = 3000; // milliseconds for speed 1
// analogWrite(motorPin, Speed1); // turns the motor On
// }
// }
// else
// {
// analogWrite(motorPin, LOW);
// }
//
// //End of yomis code
if (cm <= 10) {
int Speed1 = 150; // between 0 (stopped) and 255 (full speed)
int Time1 = 2000; // milliseconds for speed 1
int Speed2 = 250; // between 0 (stopped) and 255 (full speed)
int Time2 = 3000; // milliseconds to turn the motor off
analogWrite(motorPin, Speed1); // turns the motor On
delay(Time1); // delay for onTime milliseconds
// analogWrite(motorPin, Speed2); // turns the motor Off
// delay(Time2); // delay for offTime milliseconds
}
else if (cm > 10) {
analogWrite(motorPin, LOW); // turn the motor off
}
else {
Serial.print(inches);
Serial.print("in, ");
Serial.print(cm);
Serial.print("cm");
Serial.println();
delay(100);
}
}
long microsecondsToInches(long microseconds)
{
// According to Parallax's datasheet for the PING))), there are
// 73.746 microseconds per inch (i.e. sound travels at 1130 feet per
// second). This gives the distance travelled by the ping, outbound
// and return, so we divide by 2 to get the distance of the obstacle.m
// See: http://www.parallax.com/dl/docs/prod/acc/28015-PING-v1.3.pdf
return microseconds / 74 / 2;
}
long microsecondsToCentimeters(long microseconds)
{
// The speed of sound is 340 m/s or 29 microseconds per centimeter.
// The ping travels out and back, so to find the distance of the
// object we take half of the distance travelled.
return microseconds / 29 / 2;
}
</code></pre>
| <p>A simpler solution. Use a variable to detect the trend and another for previous distance. Initialized to false and a very large number respectively. </p>
<p>Once a new distance is available the two variables are updated. If the trend is decreasing and the distance is less than your desired distance activate the motor.</p>
|
12771 | |analogread|photoresistor| | Analog INPUT_PULLUP for resistive sensors? | 2015-06-19T13:50:06.430 | <p>Can you use the internal pull-up on an ADC pin? Is it correct usage? Example of hardware usage would be a cadmium photocell between <em>Ax</em> and <em>GND</em>. Software is the same, except declaring <em>Ax</em> as INPUT_PULLUP instead of INPUT.</p>
| <blockquote>
<p>Can you use the internal pull-up on an ADC pin?</p>
</blockquote>
<p>Yes.</p>
<blockquote>
<p>Is it correct usage?</p>
</blockquote>
<p>No. The exact pullup resistance varies from pin to pin and chip to chip, so depending on it for the high side is problematic at best.</p>
<p>Ideally you should be disabling the digital circuitry on an analog input entirely by writing to the <code>DIDR0</code> and <code>DIDR1</code> registers appropriately.</p>
|
12775 | |power|arduino-pro-mini|arduino-motor-shield|adafruit| | Pro Mini 5v with Adafruit motor shield v1 power sharing problems | 2015-06-19T15:03:22.210 | <p>I am trying to convert a RC car into autonomous car using Arduino Pro Mini 5v 16 Mhz. I have done this with UNO and Adafruit motor shield 1.0 with 4 gear motors and one micro servo for mounting range finder sensor. That worked fine. </p>
<p>Need to mention here that originally the RC car was using 5 AA cells for 2 motors and its RC reciever which looks like a customized motor shield as well.</p>
<p>I tried to move everything to Arduino Pro Mini 5v, and motor shield v1 to reduce space. Now how I wired everything.</p>
<ol>
<li>Uses 8 AA cells to power the motor shield on EXT-PWR input.</li>
<li>From EXT-PWR in motor shield one wire goes to RAW in Pro mini.</li>
<li>From Pro Mini, VCC connected to +5v on motor shield.</li>
<li>One micro servo having range sensor getting its current from motor shield.</li>
<li>Motor shield has to run two motors, 1 for rear wheels and 1 for turning front wheels. (they are small motors look like 3v)</li>
</ol>
<p>Now when I turn on the power the motor sometimes run and sometimes sound like bee and no movement. That also cause the L293d chip on motor shield becomes very hot and I think I have burnt one yesterday and replaced it from another motor shield. Same for servo it sometimes move or not move but sounds like hmmmmmmmm. The Arduino power light on and red. But sometimes it flickers and other light is also on and off. </p>
<p>At this point I have no idea whats wrong here. I changed the input voltage to lower but no progress. Tried to disconnect the 5v input from Pro Mini to motor shield and give 9v input to motor shield but nothing works. Please suggest best or correct power distribution in this case.</p>
<p>Thanks</p>
<p>Qazi</p>
| <p>Sounds good, a more capable linear regulator with heat sink. Another possibility is to get a DC to DC converter (buck regulator from 12 volts to 5 volts), that way is more energy efficient than a linear regulator. They cost just slightly more than a linear regulator on ebay, and don't need a heat sink.</p>
|
12795 | |arduino-uno|serial|bootloader| | Why the bootloader burn on ATmega328 rather than Atmega16U2 in Arduino Uno | 2015-06-20T08:03:12.600 | <p>I have been researching about the reason why we have a second MCU in arduino UNO for a while now. finally i understood that its been use as USB to serial converter. the question that really bug me now, why is the boot-loader is burn on the main ATmega328 not Atmega16U2 ? </p>
| <p>The purpose of the bootloader is to get the firmware through the serial
port and burn it into the flash. The 16U2 has no access to the 328's
flash. The job has to be done in the 328 itself.</p>
|
12805 | |pins| | What is GND on board? | 2015-06-20T15:22:11.030 | <p>I've looked in several places, and so far can not understand to want to be the GND who is on the board.</p>
<p>There is this documented anywhere?</p>
| <p>It is the 0V reference for everything else, as well as the power supply return.</p>
<p><a href="https://en.wikipedia.org/wiki/Ground_%28electricity%29" rel="nofollow">"Ground (electricity)" on Wikipedia</a></p>
|
12808 | |python| | Handle reading timing in Python using pySerial | 2015-06-20T20:29:55.317 | <p>I'm not sure about how to properly handle timing readings from serial inside a Python script. I need to read a value every <strong>5 seconds</strong>.</p>
<p>From Arduino I could do,</p>
<pre><code>Serial.println(value);
delay(5000); // should I wait here?
</code></pre>
<p>Inside Python script I could do,</p>
<pre><code>import serial
import time
arduino = serial.Serial('/dev/ttyACM1', 9600, timeout=5) # should I set timeout?
while True and arduino.isOpen():
try:
value = arduino.readline().strip()
print value
time.sleep(5) # should I wait here?
except KeyboardInterrupt:
print "\nClosing..."
arduino.close()
</code></pre>
<p>EDIT: Apart from that, the first reading is always wrong, like if there was something in the reading buffer.
I've found out that to solve that I should add <code>arduino.flushInput()</code> just after opening the port.</p>
| <p>The answer is that it depends on what you are actually trying to accomplish. If there is nothing else to be done on the Arduino then it is fine to have it sit and wait; on the other hand if there is nothing else for the python script to do then it is fine for it to sit and wait, but there is no reason for both of them wait.</p>
<h2>Arduino <code>delay</code>s</h2>
<p>You don't need to deal with the timing delay in python if the Arduino is <code>delay</code>ing. According to <a href="http://pyserial.sourceforge.net/shortintro.html#readline" rel="nofollow">the documentation</a> <code>readline</code> will wait until it has received a value or until the timeout is reached. That said, I would make the timeout slightly longer than the delay on the Arduino side of things.</p>
<p>Note that <code>readline</code> will block your program from doing anything else while it waits. As such, It is pretty useful to explore python <a href="https://docs.python.org/2/library/threading.html#module-threading" rel="nofollow"><code>threading</code></a> when you are writing a program which collects data over a serial stream unless the program is <em>only</em> collecting data. </p>
<h2>Python <code>sleep</code>s</h2>
<p>If there is other stuff to be done on the Arduino (perhaps if you are doing some filtering of the temperature data using the Arduino so as to reduce noise) then it might make more sense for it to push data to the serial stream at the end of each <code>loop</code>, and for the python script to only read the data every 5 seconds. In this case you could have python <code>sleep</code> and use no delay (or a shorter delay) on the Arduino. You can achieve this behavior without resorting to using <code>sleep</code> by using a <a href="https://docs.python.org/2/library/threading.html#timer-objects" rel="nofollow"><code>timer</code> object</a> to periodically call a function that <code>open</code>s the serial stream (possibly flush it), reads the data, processes it, and closes the serial stream. </p>
|
12809 | |simulator| | How to simulate Arduino? | 2015-06-18T12:12:31.637 | <p>QUCS is the only open source software which offers simulation (and designing PCB layout [in future]) of electrical circuits. But the problem with QUCS is that it is under development and many important features are not yet available in it.</p>
<p>I want to simulate Arduino Uno board in it for my circuit. Does anyone know how to simulate Arduino or any other micro-controller in it?</p>
<p><strong>P.S.</strong> Also any other open source software for simulation and PCB designing?</p>
| <p>Try this: <a href="https://simulide.com/p/" rel="nofollow noreferrer">simulIDE</a></p>
<p>Google: <a href="https://www.google.com/search?q=simulIDE%20for%20arduino%20picture" rel="nofollow noreferrer">simulIDE for arduino picture</a></p>
<p>Supports also: PIC, ATtiny, ATR, Arduino...</p>
|
12812 | |arduino-ide|wifi|arduino-nano|esp8266| | ESP8266 wifi module sending data via jQuery | 2015-06-21T06:38:07.107 | <p>Hey all I have the ESP8266 module and I have already set it up and it's working good. However, when I run this HTML page code here:</p>
<pre><code><html>
<head>
<title>ESP8266 LED Control</title>
</head>
<body>
<button id="6894" class="led">Toggle Pin 13</button> <!-- button for pin 13 -->
<script src="jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$(".led").click(function(){
var p = $(this).attr('id'); // get id value (i.e. pin13, pin12, or pin11)
$.get("http://192.168.9.60:80/", {pin:p}); // execute get request
});
});
</script>
</body>
</html>
</code></pre>
<p>I have to send the number 6894 instead of 13 because for some reason its not sending out the correct number. If i send 13 then what it receive is 114. When i send 6894 i receive 689.</p>
<p>My arduino code is this:</p>
<pre><code>*/
//====================================================================================
// [The SSDI of the current wifi router]
// | [The password of the current wifi router]
// | |
// V V
String SSIDandPW = "AT+CWJAP=\"xxxxxxwifi\",\"xxxxxx123\"\r\n";
// [The STATIC IP of the wifi module]
// | [The main IP of the router]
// | | [The default submask]
// | | |
// V V V
String eIPrIPmask = "AT+CIPSTA_DEF=\"192.168.9.60\",\"192.168.9.1\",\"255.255.255.0\"\r\n";
const int ledDimmer = 5; // Used to dim the LED strip (digital Pin 3)
SoftwareSerial esp8266(9,10); // Pin D10 to=> TX on ESP8266 | Pin D9 to=> RX on ESP8266
//================================= End define WiFi Module =================================
//==========================================================================================
void setup() {
Serial.begin(19200);
pinMode(13, OUTPUT); //Just for a wifi demo from html page
//================================ Start Setup WiFi Module =================================
//==========================================================================================
esp8266.begin(19200);
sendData("AT+RST\r\n", 2000, true); // Reset module
sendData("AT+CWMODE=1\r\n", 2000, true); // Configure as access point
sendData(SSIDandPW, 5000, true); // Pass of current wifi
sendData("AT+CIPMUX=1\r\n", 2000, true); // Configure for multiple connections
sendData("AT+UART_DEF=19200,8,1,0,0\r\n", 2000, true); // Set baud of COM
sendData(eIPrIPmask, 2000, true); // Default network mask IP
sendData("AT+CIPSERVER=1,80\r\n", 2000, true); // Turn on server on port 80
sendData("AT+GMR\r\n", 2000, true); // Get firmware version
sendData("AT+CIFSR\r\n", 2000, true); // Get ip address
Serial.print("Server is now running!");
//================================ End Setup WiFi Module ===================================
//==========================================================================================
}
void loop() {
//=========================================== Start Loop WiFi Module ===========================================
//==============================================================================================================
if(esp8266.available()) { // check if the esp is sending a message
if(esp8266.find("+IPD,")) {
delay(500);
int connectionId = esp8266.read() - 48; // subtract 48 because the read() function returns
esp8266.find("pin="); // advance cursor to "pin="
int retunedNum = (esp8266.read() - 48) * 100; // get first number (example: 123.. this would be "1")
retunedNum += (esp8266.read() - 48) * 10; // get second number (example: 123.. this would be "2")
retunedNum += (esp8266.read() - 48); // get last number (example: 123.. this would be "3")
String closeCommand = "AT+CIPCLOSE="; // make close command
Serial.print("returned: ");
Serial.print(retunedNum);
Serial.print("----------");
closeCommand += connectionId; // append connection id
closeCommand += "\r\n";
sendData(closeCommand, 250, true); // close connection
//digitalWrite(retunedNum, !digitalRead(retunedNum)); // toggle pin
if (retunedNum == 6894) {
Serial.print("OFF");
digitalWrite(ledDimmer, LOW);
} else if (retunedNum == 6904) {
Serial.print("ON");
digitalWrite(ledDimmer, HIGH);
} else if (retunedNum == 689) {
digitalWrite(13, HIGH); // turn the LED on (HIGH is the voltage level)
delay(1000); // wait for a second
digitalWrite(13, LOW); // turn the LED off by making the voltage LOW
delay(1000); // wait for a second
}
}
}
//============================================ End Loop WiFi Module ============================================
//==============================================================================================================
}
// [The data/command to send]
// | [The time to wait for a response]
// | | [Print to Serial window (true = yes | false = no)]
// | | |
// V V V
String sendData(String command, const int timeout, boolean debug) {
String response = "";
long int time = millis();
esp8266.print(command); // send the read character to the esp8266
while((time + timeout) > millis()) {
while(esp8266.available()) {
// The esp has data so display its output to the serial window
char c = esp8266.read(); // read the next character.
response += c;
}
}
if (debug) { Serial.print('Returned: ' + response); }
return response;
}
</code></pre>
<p>And the console output is this:</p>
<pre><code>14880AT+RST
OK
14880
"qXÑ{ÂB!É
1±þ)ÒBÙa
+ò“H!a5)�#)ÒÂia%YakN‘ J!ÐCÊ!�
÷þˆ2ô
ready
14880AT+CWJAP="xxxxxxwifi","xxxxxx123"
OK
14880AT+CIPMUX=1
OK
14880AT+UART_DEF=19200,8,1,0,0
OK
14880AT+CIPSTA_DEF="192.168.9.60","192.168.9.1","255.255.255.0"
OK
14880AT+CIPSERVER=1,80
OK
14880AT+GMR
AT version:0.22.0.0(Mar 20 2015 10:04:26)
SDK version:1.0.0
compile time:Mar 20 2015 11:00:56
OK
14880AT+CIFSR
+CIFSR:STAIP,"192.168.9.60"
+CIFSR:STAMAC,"18:fe:34:9b:4e:68"
OK
Server is now running!
returned: 689----------148804 HTTP/1.1
Host: 192.168.9.60
Connection: AT+CIPCLOSE=0
0,CLOSED
OK
</code></pre>
<p>What I really am wanting to do is have a way to send a 10 charater string to the arduino instead of the limited 3 numbers above. I just am not sure what i need to add/modify in order to make it see letters/numbers and only the first 10 that i send.</p>
<p>Any help would be great!</p>
| <pre><code> int retunedNum = (esp8266.read() - 48) * 100; // get first number (example: 123.. this would be "1")
retunedNum += (esp8266.read() - 48) * 10; // get second number (example: 123.. this would be "2")
retunedNum += (esp8266.read() - 48); // get last number (example: 123.. this would be "3")
</code></pre>
<p>Your code always expects the pin number to have 3 digits.</p>
<p>In case of 13, it takes a space character as the last digit.<br>
It reads charachters '1', '3' and ' '. Their ASCII codes are 49, 51 and 32. With this, the calculated number is</p>
<pre><code>(49 - 48) * 100 + (51 - 48) * 10 + (32 - 48) = 114.
</code></pre>
<p>With 6894, it just uses the first three digits and ignores the last.</p>
<p>For 1 or 2 digit long number you could just pad it with '0' character i.g. "013".</p>
<p>If you want to read an arbitrary string, you should replace the above code with this code:</p>
<pre><code>String retunedStr = "";
for(;;) {
char c = esp8266.read();
if (c == ' ')
break;
retunedStr += c;
}
</code></pre>
<p>And obviously replace</p>
<pre><code>Serial.print(retunedNum);
</code></pre>
<p>with</p>
<pre><code>Serial.print(retunedStr);
</code></pre>
<p>With this, you should only use letters (A-Z, a-z), numbers (0-9), dash (-) and an underscore (_) for the string.<br>
If you use other characters, you could have problems with the URL character encoding.</p>
|
12820 | |arduino-uno|ethernet|arduino-micro| | micro arduino and w5100 | 2015-06-21T21:15:35.470 | <p>I would like to ask if it is possible and how to connect the following module
<a href="http://www.ebay.com/itm/TOP-Mini-W5100-LAN-Ethernet-Shield-Network-Module-board-for-Arduino-Best-NEW-/251981053942?pt=LH_DefaultDomain_0&hash=item3aab3dbff6" rel="nofollow">http://www.ebay.com/itm/TOP-Mini-W5100-LAN-Ethernet-Shield-Network-Module-board-for-Arduino-Best-NEW-/251981053942?pt=LH_DefaultDomain_0&hash=item3aab3dbff6</a></p>
<p>to the arduino micro </p>
<p>I found some pin layouts but only for Leonardo or Ethernet shield, Uno etc.</p>
<p>Also I've choosen this model because it can be programmed directly in arduino using Sockets API</p>
| <p>While it would have been nice to see your research rather then having to spend some time finding this information myself, I did find this <a href="http://www.instructables.com/id/Add-Ethernet-to-any-Arduino-project-for-less-than-/" rel="nofollow">http://www.instructables.com/id/Add-Ethernet-to-any-Arduino-project-for-less-than-/</a> from what I can see this should be compatible to any arduino as long as it has 3 volt pin and 4 i/o pins. While the arduino micro doesn't have a 3v3 pin, as far as I know, that shouldn't be an issue as long as you can drop the voltage from the 5 volt pin, this module should work for you.</p>
|
12821 | |arduino-uno|c++|library| | Malloc with Objects in Arduino libraries | 2015-06-21T21:45:59.823 | <p>My understanding of using dynamic memory on the arduino is that new/delete are not available, only malloc realloc and such C functions, as mentioned here:</p>
<p><a href="http://www.nongnu.org/avr-libc/user-manual/FAQ.html#faq_cplusplus" rel="nofollow noreferrer">C++ & the AVR</a></p>
<p>I am creating a library that defines an object type that needs to contain a dynamic list of other objects. In C++ I would define it something like this:</p>
<pre><code>class Container
{
std::vector<otherObjectType> otherObjects;
};
</code></pre>
<p>which obviously does not work in the arduino without the C++ standard library.</p>
<p>My next choice would be to create a dynamic array using new, ie</p>
<pre><code>otherObjects = new otherObjectType[3]
{
{ (arguments to constructor...)
},
{ (arguments to constructor...)
},
{ (arguments to constructor...)
}
};
</code></pre>
<p>But this does not work as well, since new is not supported...</p>
<p>finally I could try to use malloc as laid out <a href="https://stackoverflow.com/questions/4956249/using-malloc-instead-of-new-and-calling-the-copy-constructor-when-the-object-is">here</a>, but that also wont work without new.</p>
<p>I am wondering if I should just rewrite everything as structs, since that wont require me to worry about whether the constructor for the object was called when the memory was allocated in malloc.</p>
| <p><code>new</code> actually does work in arduino. it is defined in arduino/hardware/arduino/avr/cores/arduino/{new.h, new.cpp} using malloc. It is not part of avr-libc though (which your link concerns) and has not always been added by arduino.</p>
<p>Both of these work for me:</p>
<pre><code>namespace{ //namespace to deal with .ino preprocessor bug
class foo{
public:
int bar;
foo(int a){
bar = a;
}
};
}
...
//using new
foo *a = new foo[3]{{1},{2},{3}};
//How I would probably do this with malloc
foo *b = (foo*) malloc(sizeof(foo)*3);
b[0] = foo(2);
b[1] = foo(4);
b[2] = foo(8);
</code></pre>
<p>Placement new is not defined right now. I know that copying isn't quite the same, but it should work in most cases.</p>
<p>Of course, if you know exactly how long you want the array to be at compile time, you should probably make it a static/global variable so that you avoid using dynamic memory and the sketch ram usage number will be closer to correct.</p>
|
12834 | |arduino-uno|sensors| | Change input reference to 1 - 5 V | 2015-06-22T07:10:46.280 | <p>I am using a sensor which delivers a 4 to 20 mA output.
Converting this with a 250 Ohm resistor to ground I convert this to a 1 - 5 V output.</p>
<p>My question how can I change the 0V reference, so I can use the full spectrum
I found a way to change the 5V reference (analogReference()).
Is it possible to change the 0V reference of a input to 1V?</p>
<p>Any other solution to my problem is welcome as well! (As long as it doesn't involve I2C or anything which lowers my looptime drastically)</p>
| <p>The ADC is ground-referenced, and there's no way to change that. The question is if that's necessary. The ADC has a 10-bit resolution, that's good for 1024 different levels between 0 and 5 V. If you convert the 4-20mA with a 250 Ω resistor to a 1-5 V range you still can discriminate between more than 800 different values. </p>
<p>If that's not enough you can use a differential amplifier to subtract 1 V:</p>
<p><img src="https://i.stack.imgur.com/wV1zG.gif" alt="enter image description here"></p>
<p>By choosing R3 = 1.25 R1 you convert the 0-4 V range to a 0-5 V range.</p>
|
12842 | |sensors|accelerometer|gyroscope|magnetometer| | What is the difference between Accelerometer, Gyro, and Magnetometer Sensor? | 2015-06-22T13:58:52.397 | <p>I'm starting in the arduino world and I'm building an autonomous smart vehicle.</p>
<p>So, after some weeks building and adjusting the vehicle, I got to a point in this project that I want to log it's movements. Talking with a friend, he showed me an Gyro/Accel sensor and I really think that it would be an awesome upgrade to my vehicle</p>
<p>After reading some articles, I'm failing to understand the difference between an <strong>Accelerometer Sensor</strong>, a <strong>Gyro Sensor</strong> and a <strong>Magnetometer Sensor</strong></p>
<p>So what is the main difference between those sensors?</p>
| <p>The Accelerometer measures total acceleration on the vehicle, including the static acceleration from gravity it would experience even when its not moving. </p>
<p>The magnetometer measures the magnetic field around the robot, including the static magnetic field pointing approximately north caused by the earth. Being placed in/around a metal frame or any large motors, diving over/around underground metal pipes or electrical equipment will all make large and noticeable effects on its measurements.</p>
<p>The Gyroscope measures your instantaneous angular momentum around each axis, basically how fast its rotating. Note that angular momentum is not directly compatible with euler angles, but works out similarly for small angles. Very high quality signal in the short term because there isn't much noise, but since your angular position has to be integrated off of the gyroscope, it will build up error.</p>
<p>Gravity is your best reference for angular position, because it doesn't drift like the gyroscope and since your robot is operating in (and causing) a sea of magnetic disturbances, using north is risky. It will not work if you are experiencing a significant acceleration though.</p>
<p>The simplest code would just use the accelerometer for rotations around x and y, the mag for z, and ignore disturbances. The basic idea is "I know gravity is actually down, but its being measured on the accel X axis, so I must be pitched by some amount". The Better sensor fusion algorithms will use the accelerometer/magnetometer to correct for drift in the gyro, but get most of its information about rotational position from the Gyroscope.</p>
<p>Tracking lateral position using a standard 9-dof IMU is not possible. Only the accelerometer measures lateral motion at all, and it needs to be integrated twice to get position. Error builds so fast your position estimate is complete garbage within seconds.</p>
<p>Tracking angular position is possible because all three sensors measure it in one way or another. Angles are tricky though because they are not commutative. If the gyro measures a 90 degree yaw then a 90 degree pitch from north, you are facing down; if it measures a 90 degree pitch and then a 90 degree yaw from north, your facing east turned on your side. Be careful with the math, or download an arduino IMU library that has it taken care of for you.</p>
|
12854 | |arduino-uno|arduino-nano| | Fried two Arduino Nano's but works when powered | 2015-06-23T10:41:28.457 | <p>It took me about 4 hours to desolder an Arduino Nano I fried and solder on the new one. I'm not exactly sure how but I shorted it somehow while trying to install the nano onto my robot. I could smell a fait burning and the nano no longer powered on or allowed me to upload code via USB. </p>
<p>When I put the second nano on, before properly insulating exposed wire, I fried it again!! This time I actually saw a little smoke and quickly unplugged it. The nano no longer responds to the USB, but...</p>
<p>I have this nano also being powered by an Arduino Uno. When I turned on the battery connected to the Uno, the Nano turned on and everything was working fine!! I was pretty relieved after a short spout of depression! I plugged in the USB to the Nano and I was able to upload code... only with the nano being powered from the Uno. If I turn off the battery to the Uno the Nano doesn't work with USB.</p>
<p>I have no idea what happened exactly and I'm not sure what fried on my Nano but I sure am glad I have this work around instead of replacing the Nano again! </p>
<p>Does anyone know why it's doing this? What did I see smoking? Is it repairable? </p>
| <p>Judging by your list of observations:</p>
<ul>
<li>Cannot power through USB</li>
<li>Can power from external source</li>
<li>Can program through USB</li>
</ul>
<p>it is most likely that the power feed from the USB to the +5V rail has been interrupted. There is only one component in that link - the diode D1 (an MBR0520). That is rated at an absolute maximum constant forward current of 0.5A and most USB ports these days are capable of providing far more than that. A short circuit on the +5V to ground would draw considerably more current than that diode can handle and the Magic Smoke™ would escape.</p>
<p>The diode is on the underside of the Micro and close examination may show a small crack in the surface of it. That is if it's still there. I have used a similar PIC32 based board with 0.5A rated diodes on it, and a short of the power rail when powered from USB caused the diode to completely vaporise (at least I could find no trace of it afterwards).</p>
|
12856 | |arduino-uno|accelerometer| | is any windows application available for accelerometer based computer mouse | 2015-06-23T11:32:13.610 | <p>I want to make an AIR mouse using Arduino
and accelerometer, for this i used USB to TTL
converter i have done everything successfully
but can anyone tell me how use it in computer.
I mean i don't know how to make computer
application for this mouse. please suggest me
any application for this. And give any idea for
"how can i use Bluetooth for this."</p>
| <p>......................................
......................................</p>
|
12879 | |button|digital|shift-register| | Using shiftin() and shiftout() with the same circuit - what to consider? | 2015-06-24T00:37:00.290 | <p>I am designing a smart (or at least I hope so) onboard bicycle light system. The system will have an Arduino (currently prototyping with UNO) and a subsystem composed of a "panel" of buttons and leds.</p>
<p>This panel should stay at the handlebar, connected by multi-wire cable to the Arduino located elsewhere on the bicycle.</p>
<p>In order to read an arbitrary number of push-buttons, I plan to use CD4021 IC with <code>shiftIn()</code> function. And, in order to turn an arbitrary number of leds on and off, I plan to use 74HC595 IC and the <code>shiftOut()</code> function.</p>
<p>My doubts are: what should I consider in order to do so?</p>
<ol>
<li><p>How many wires should I need to connect an arduino to the panel circuit containing the ICs? I believe it is 8 wires (two for the power, three for shifting in [latch, clock, data], and three for shifting out), right?</p></li>
<li><p>Can I use any pin I want? Or is it required to use specific pins?</p></li>
<li><p>Is that the "right way" of doing this? Any suggestion or improvement is welcome!</p></li>
</ol>
| <p>I have a post here about using an I2C 16-port port-expander: <a href="http://www.gammon.com.au/forum/?id=10945" rel="nofollow">http://www.gammon.com.au/forum/?id=10945</a></p>
<p>That would use 4 wires for I2C (power, ground, SDA, SCL) or there is an SPI version which would require an extra wire (power, ground, SCK, MOSI, MISO).</p>
<p>I'm not sure about noise over your cable runs, on a bicycle presumably electrical noise is low, so either one might suit. This is the chip that Ignacio Vazquez-Abrams mentioned in his comments. Any of the 16 ports can be configured as inputs or outputs as you desire, plus it can raise an interrupt on a change on an input pin.</p>
<p>You might find that the maximum current limits for output may not be adequate for your LEDs (the datasheet says maximum of 25 mA per output pin, plus a maximum of 125 mA for the whole chip). You could work around this with driver transistors on the chip output, but this is more complexity.</p>
<p>There are higher-powered shift registers (eg. TPIC6B595) which can handle more per pin than the 74HC595.</p>
<blockquote>
<p>Can I use any pin I want? Or is it required to use specific pins?</p>
</blockquote>
<p>If you want to use I2C there are two specific pins dedicated to the I2C hardware. If you want to use SPI there are dedicated hardware pins as well (different ones) but you can also "bit-bang" SPI if you want.</p>
<p>See: </p>
<p><a href="http://www.gammon.com.au/i2c" rel="nofollow">http://www.gammon.com.au/i2c</a></p>
<p><a href="http://www.gammon.com.au/spi" rel="nofollow">http://www.gammon.com.au/spi</a></p>
<blockquote>
<p>Is there a through-hole version of that?</p>
</blockquote>
<p>All the chips I mention here have through-hole versions.</p>
|
12882 | |arduino-uno|avrdude|reset| | How does the reset button work on the Arduino? | 2015-06-24T09:29:03.533 | <p>I'm confused about how and when to use the reset button on the Arduino. Do I simply press the button while it is on? Is it simply restarting the board or clearing the uploaded code as well? Currently when I press the button while my Uno is powered it does absolutely nothing. </p>
<p>I have been using this board for many weeks with no problem and just now I have been getting this error:</p>
<pre><code>avrdude: stk500_getsync()
</code></pre>
<p>And I cannot upload code. I tried using the reset button but I see nothing happening on the board, no blink, no flicker, nothing indicating something was reset. </p>
| <p>The reset button does pretty much the same as unplugging the board and plugging it back in. It restarts your program from the beginning. </p>
<p>The same thing happens when you program the board - the USB interface presses the reset button for you. That then enters the bootloader for a second or two so it can try and program it.</p>
<p>When you reset the board the LED on pin 13 should flash a couple of times while it's in the bootloader before it runs whatever program you have programmed in. If that LED doesn't flash when you press the reset button then there is a serious fault with your board which will take further diagnostic.</p>
<ul>
<li>If you have anything else plugged into the Arduino then unplug it.</li>
<li>Try powering the Arduino from different power supplies.</li>
<li>If you have another Arduino or an AVR programmer try re-flashing the bootloader.</li>
</ul>
|
12892 | |arduino-uno| | Strange phenomenon when declaring double | 2015-06-24T13:19:05.830 | <p><strong>Consider this question closed, found my answer through the answers I had</strong></p>
<p>I am trying to make a position profile curve depending on Looptime, accelerationloops,Setposition,Currentposition(position) and velocity.
The curve should look like this:</p>
<p><img src="https://i.stack.imgur.com/VttgJ.jpg" alt="enter image description here"></p>
<p>Is someone able to check what is wrong with my code?</p>
<pre><code>float array[30];
struct Formula {
int LoopTime = 1000;
int AccelerationLoops = 11;
float VelocityLoop = 0;
float VelocityFactor = 0;
int TotalLoops = 0;
float DeltaPosition = 0;
int Setpoint = 0;
int Iteration = -1;
float EndOne = 1.25;
}Formula;
float SetPosition = 1404;
float Position = 0;
float Velocity = 36;
void setup() {
Serial.begin(115200);
for(Formula.Iteration ; Formula.Iteration <= Formula.TotalLoops; Formula.Iteration++){
ProgFormula();
Serial.println(Formula.Iteration);
if(Formula.Iteration >= 0) {array[Formula.Iteration] = Formula.Setpoint;}
}
for(Formula.Iteration = 0 ; Formula.Iteration <= Formula.TotalLoops; Formula.Iteration++){
//Serial.println(array[Formula.Iteration]);
}
}
void loop() {
// put your main code here, to run repeatedly:
}
void ProgFormula(){
if(Formula.Iteration == -1) {
Formula.DeltaPosition = SetPosition - Position;
Formula.VelocityLoop = Velocity / (1000 / Formula.LoopTime);
Formula.TotalLoops = Formula.DeltaPosition / Formula.VelocityLoop + Formula.AccelerationLoops;
Formula.VelocityFactor = Formula.VelocityLoop * 0.5 / Formula.AccelerationLoops;
Formula.EndOne = (Formula.VelocityFactor*pow(Formula.AccelerationLoops,2));
}
else if (Formula.Iteration >= 0 && Formula.Iteration <= Formula.AccelerationLoops) {
Formula.Setpoint = Formula.VelocityFactor * pow(Formula.Iteration,2);
}
else if (Formula.Iteration > Formula.AccelerationLoops && Formula.Iteration <= (Formula.TotalLoops - Formula.AccelerationLoops)) {
Formula.Setpoint = Formula.VelocityLoop * Formula.Iteration - Formula.EndOne;
}
else if (Formula.Iteration >= (Formula.TotalLoops - Formula.AccelerationLoops) && Formula.Iteration <= Formula.TotalLoops) {
Formula.Setpoint = -Formula.VelocityFactor * pow((Formula.TotalLoops - Formula.Iteration),2) + Formula.DeltaPosition;
}
else {
Formula.Setpoint = Formula.Setpoint;
}
}
</code></pre>
| <p>OK, this may not be a proper answer. I'm just having a hard time reading
your code, and I cannot understand why you make it so complicated. If
you know the acceleration profile, computing the position profile is
just a matter of integrating twice. Here is an example, not for Arduino
but for a PC. It should not be very different on an Arduino, you just
wouldn't use <code>printf()</code>:</p>
<pre class="lang-c++ prettyprint-override"><code>/* Compute position for any acceleration profile. */
void compute_profile(float (*acceleration)(int), int max)
{
float x = 0, v = 0;
for (int t = 0; t <= max; t++) {
v += acceleration(t);
x += v;
printf("%d\t%f\n", t, x);
}
}
/* Your particular acceleration profile. */
float VttgJ(int t)
{
if (t < 7) return t;
if (t < 13) return 12 - t;
if (t < 40) return 0;
if (t < 46) return 39 - t;
else return t - 51;
}
int main(void)
{
compute_profile(VttgJ, 50);
return 0;
}
</code></pre>
|
12910 | |arduino-uno|serial|bluetooth|pins|ftdi| | BLE Mate 2 bluetooth module to Arduino Uno without FTDI SmartBasic | 2015-06-25T15:15:22.580 | <p>So I'm trying to hook up this <a href="https://www.sparkfun.com/products/13019" rel="nofollow">BLE breakout board</a> to an Arduino Uno. SparkFun has a <a href="https://learn.sparkfun.com/tutorials/bc118-ble-mate-2-hookup-guide?_ga=1.207897426.1342547721.1435176975" rel="nofollow">hookup guide</a> which seems to be great for someone who has an FTDI SmartBasic that is mentioned in the article. I don't have the SmartBasic board, and would like to see if this is possible without it.</p>
<p>I have hooked up the board to my Uno with the following pinouts:</p>
<pre><code>GRN -> Reset
RXI -> RX (tried with TX as well)
TXI -> TX (tried with RX as well)
VIN -> Tried 5V and 3.3V
CTS -> GND
BLK -> (No Connection)
</code></pre>
<p>I use their <a href="https://github.com/sparkfun/SparkFun_BLE_Mate2_Arduino_Library" rel="nofollow">example code</a> they have provided, uploaded without the RX and TX pins hooked up because, from what I notice, you cannot upload a program through the USB serial when these ports are in use. So after I upload the program through USB, I power the board with a battery and connect the RX and TX pins to the BLE board.</p>
<p>Has anyone either successfully hooked these up without the use of a SmartBasic? I'm a programmer by trade so I do my best to understand this side of the spectrum.</p>
| <p>So I found out what I was doing wrong, and want to smack myself for it -.-</p>
<p>The answer was to simply hook up the BLK connection (which I guess is also ground) to a GND pin on the Arduino Uno.</p>
<p>Hope this ends up helping someone out.</p>
|
12915 | |arduino-uno|timers| | Timer function without the use of a library | 2015-06-26T04:27:22.277 | <p>Trying to do my own timer function. I was wondering if there is any other ways to make my code more efficient without the use of a library. I noticed if I only use one timer function, I wont have multiple instances of the timer. My current code works though.</p>
<pre><code>unsigned long previousMillis1 = 0;
unsigned long currentMillis1 = millis();
unsigned long previousMillis2 = 0;
unsigned long currentMillis2 = millis();
unsigned long previousMillis3 = 0;
unsigned long currentMillis3 = millis();
bool timer1(int preset){
unsigned long currentMillis1 = millis();
if(currentMillis1 - previousMillis1 >= preset ){
previousMillis1 = currentMillis1;
return true;
}
else{
return false;
}
}
bool timer2(int preset){
unsigned long currentMillis2 = millis();
if(currentMillis2 - previousMillis2 >= preset ){
previousMillis2 = currentMillis2;
return true;
}
else{
return false;
}
}
bool timer3(int preset){
unsigned long currentMillis3 = millis();
if(currentMillis3 - previousMillis3 >= preset ){
previousMillis3 = currentMillis3;
return true;
}
else{
return false;
}
}
void setup() {
Serial.begin(9600);
}
void loop() {
if(timer1(1000)){Serial.println(1);}
if(timer2(2000)){Serial.println(2);}
if(timer3(3000)){Serial.println(3);}
}
</code></pre>
| <p>Happened across <a href="https://oscarliang.com/arduino-timer-and-interrupt-tutorial/" rel="nofollow">this page</a> which explains Arduino timer interrupts with out using any libraries. The Atmel timer hardware is discussed and the sketches not only control the hardware directly but also include the actual interrupt service routine. So addresses the OP's question very well.</p>
|
12922 | |code-optimization| | Simple question about && vs || | 2015-06-26T11:00:05.873 | <p>I want to skip all <code>'\r'</code> and <code>'\n'</code> chars and I have IF statment:</p>
<pre><code>char c = Serial.read();
if (c != '\r' || c != '\n') { // <- This line interesting
mAnswer[mAnswerLength] = c;
mAnswerLength++;
}
</code></pre>
<p>VS</p>
<pre><code>char c = Serial.read();
if (c != '\r' && c != '\n') { // <- This line interesting
mAnswer[mAnswerLength] = c;
mAnswerLength++;
}
</code></pre>
<p>What is better and what is the difference?</p>
| <p>You can rewrite first condition to be more obvious</p>
<pre><code>if (c != '\r' || c != '\n') {
</code></pre>
<p>as</p>
<pre><code>if (!(c == '\r' && c == '\n')) {
</code></pre>
<p>Which is always true (<code>c</code> have only one value), i.e. it makes no sense.</p>
|
12951 | |pull-up| | Testing tri-state pin - erroneous results with internal pullup | 2015-06-28T00:16:51.957 | <p>I'm using an MPC73831 - a LiPo charging IC - in my Arduino project. It has a <code>status</code> pin to allow interface to a microcontroller, which uses a tri-state operation to convey three possible states of charging. I don't have the IC and battery yet, but I wanted to write a quick program to test a generic tri-state pin for HI, LO, and HiZ while I'm waiting for it to arrive.</p>
<p>The algorithm I wrote is very simple:</p>
<pre><code>Set pinTest to input, no pullup.
Is pinTest high?
Yes - pinTriState is HIGH, done.
Set pinTest to input with pullup.
Is pinTest high?
Yes - pinTriState is HiZ, internal pullup causes high reading.
No - pinTriState is LOW, 'cancelling out' internal pullup.
</code></pre>
<p>However, I'm not getting the expected results when using the internal pullup resistor - my board is showing correct analysis for HI and LO, but HiZ returns a mixture of HiZ and HIGH. I have tried this on an Uno, a Pro-Micro (32u4) and Uno->Micro and Micro->Uno. All give the same spurious results. I am baffled, therefore some advice would be appreciated. The full code is as below. I have left in code which randomises the time <code>pinTriState</code> stays at in a given state to keep <code>pinTest</code> guessing, but it's ultimately only an elaborate way of cycling through the three states.</p>
<pre><code>#define pinTest 2
#define pinTriState 3
int state = 0;
char stateCh = '?';
int sect1;
int sect2;
int sectMax;
void setup()
{
Serial.begin(9600);
randomSeed(analogRead(A0));
sect1 = random(1, 20);
sect2 = random(sect1 + 1, random(sect1 + 2, sect1 + 20));
sectMax = random(sect2 + 1, random(sect2 + 2, sect2 + 20));
}
void loop()
{
// PART (1) Code to toggle three states of a tri-state pin
if (state == 0)
{
pinMode(pinTriState, OUTPUT);
digitalWrite(pinTriState, HIGH);
stateCh = 'H';
}
if (state == sect1)
{
pinMode(pinTriState, OUTPUT);
digitalWrite(pinTriState, LOW);
stateCh = 'L'
}
if (state == sect2)
{
pinMode(pinTriState, INPUT);
stateCh = 'Z';
}
// PART (2) Code to determine state of tri-state pin
Serial.print(stateCh); // Shows what it *should* be
pinMode(pinTest, INPUT);
if (digitalRead(pinTest))
Serial.println(" - HIGH");
else
{
pinMode(pinTest, INPUT_PULLUP);
if (digitalRead(pinTest))
Serial.println(" - HiZ");
else
Serial.println(" - LOW");
}
(state == sectMax ? state = 0 : state++);
}
</code></pre>
<p>The necessary pins are connected with a single wire. If I upload the code to two boards I remove <em>PART (2)</em> on the 'triState' board and <em>PART (1)</em> on the 'testing' board. In this case, <code>stateCh</code> has no function.</p>
<p>For a single-board setup, I get the following output:</p>
<pre><code>H - HIGH
H - HIGH
...
L - LOW
L - LOW
...
Z - HiZ <-- the first Z is correct 95% of the time
Z - HIGH
Z - HIGH <-- the remaining Zs are a mixture, biased heavily towards HIGH.
Z - HiZ
...
H - HIGH <-- H always gives HIGH
...
</code></pre>
<p>It makes no difference if I change the operating order of <code>pinState</code>. I've thrown in <code>delay(100);</code> between almost every other line, again to no avail.</p>
<p>I tried with a 22k, a 33k, and a 47k <em>external</em> pullup resistor. The results are perfect. However, this requires an extra Arduino pin to make sure that the pullup is only active when necessary. <em>Part (2)</em> becomes:</p>
<pre><code>// PART (2) Code to determine state of tri-state pin
Serial.print(stateCh); // Shows what it *should* be
pinMode(pinTest, INPUT);
pinMode(pinPullup, INPUT); // connected to pinTest via resistor
if (digitalRead(pinTest))
Serial.println(" - HIGH");
else
{
//pinMode(pinTest, INPUT_PULLUP); <-- not anymore
pinMode(pinPullup, OUTPUT);
digitalWrite(pinPullup, HIGH); // pulls pinTest to Vdd
if (digitalRead(pinTest))
Serial.println(" - HiZ");
else
Serial.println(" - LOW");
}
</code></pre>
<p>Using the extra pin to provide the pullup is a real pain in the ar...duino. I'm cripplingly short of spare pins and I don't see why this is not resolvable with internal pullups. Help?!</p>
| <p>Nick Gammon's answer seems the most straightforward solution to your
problem, given that you cannot spare an analog input. It has however the
drawback of needing a delay of ≈ 100 µs. This may not be an
issue, but I just figured out a scheme that allows a faster read, and
may be of interest to some: instead of pull-ups or pull-downs, put just
a 10 kΩ resistor <em>in series</em> between the MPC73831's output and you
Arduino input. When you want to read the state:</p>
<ol>
<li>Take a first reading with the pin in INPUT mode:
<ul>
<li>if you read HIGH, then your MPC is either HIGH or HI_Z</li>
<li>if you read LOW, then it's either LOW or HI_Z</li>
</ul></li>
<li>Now, switch the pin to OUTPUT, write the <em>opposite</em> of what you just
read, switch back to input and take a second reading:
<ul>
<li>if you read what you just wrote, then your MPC is in the HI_Z state</li>
<li>if you read the same as before, then it's either HIGH or LOW.</li>
</ul></li>
</ol>
<p>Here is the implementation of this scheme:</p>
<pre class="lang-c++ prettyprint-override"><code>#define HI_Z 2
/*
* Read a 3-state pin.
* Put a 10 kOhm resistor between the output and input pins.
*/
int read3state(int pin)
{
int reading1 = digitalRead(pin);
pinMode(pin, OUTPUT);
digitalWrite(pin, !reading1);
pinMode(pin, INPUT);
int reading2 = digitalRead(pin);
if (reading1 == reading2)
return reading1;
else
return HI_Z;
}
</code></pre>
<p>I have tested this a few 10<sup>4</sup> times with an Arduino sending to
itself a pseudo-random sequence of LOW, HIGH and HI_Z. It works
reliably for me.</p>
<p><strong>Caveat</strong>: This scheme relies on the pin being capacitively coupled to
GND or Vcc, and this coupling being stronger than couplings with other
signals in your circuit. If you fear this might not be the case, you can
put something like 100 pF from the pin to ground, but then you
should better wait a couple of microseconds before taking the second
reading.</p>
|
12964 | |lcd|display| | LCD-Display showing wrong numbers | 2015-06-28T14:13:50.240 | <p>Hy guys,</p>
<p>I am having an issue with my new LCD16x2 display. I connected a potentiometer and read the values. The values are properly read and send to Serial. I also display the values on the display. I am having no issues when increasing the values, but when I go down again at a certain point the displays doesn't display the correct value anymore, but on the Serial I can still see the right readings.</p>
<p>I suppose this has something to do with the display still storing previous values for this digit in the buffer and when I go down the values are not properly reset. But I don't wan't to clear the whole buffer, since then the whole thing just blinks every iteration.</p>
<p>Here's my code</p>
<pre><code>// ESC_Calibration.ino
#include <Wire.h>
#include <Adafruit_MCP23017.h>
#include <Adafruit_RGBLCDShield.h>
#include <Servo.h>
#define WHITE 0x7
Servo firstESC;
Servo secondESC;
int throttlePin = 2;
int firstESCPin = 2;
int secondESCPin = 3;
Adafruit_RGBLCDShield lcd = Adafruit_RGBLCDShield();
void setup() {
Serial.begin(9600);
lcd.begin(16, 2);
lcd.setBacklight(WHITE);
lcd.setCursor(0, 0);
lcd.print("throttle:");
firstESC.attach(firstESCPin);
secondESC.attach(secondESCPin);
}
void loop() {
int throttle = analogRead(throttlePin);
throttle = map(throttle, 0, 1023, 0, 179);
lcd.setCursor(0, 1);
Serial.println(throttle);
lcd.setCursor(0, 1);
lcd.print(throttle);
firstESC.write(throttle);
secondESC.write(throttle);
delay(500);
}
</code></pre>
<p>Does anyone have a suggestion how to improve this and fix it, so it'll display the right readings, but doesn't blink?</p>
<p>Thanks for your help in advance! :-)</p>
| <p>As you have surmised, the problem is that the LCD retains what was there before and you need to clear it away.</p>
<p>That means, as the numbers increase you get, say,</p>
<pre><code>4
10
48
89
194
309
</code></pre>
<p>etc.</p>
<p>When they go down though, because the LCD remembers what was there, only the characters you print will be replaced:</p>
<pre><code>309 (309)
194 (194)
894 (89 - the 4 remains from before)
484 (48 - the 4 remains from before)
104 (10 - the 4 remains from before)
404 (4 - the 04 remains from before)
</code></pre>
<p>Also, as you have noticed, clearing the whole screen is not very nice since it makes it flash.</p>
<p>To combat that it is important that you only overwrite the characters that you need to overwrite and leave those that want to stay. There's two common ways of doing this:</p>
<ol>
<li><p>Append enough spaces after the number to force an overwrite:
<code>
lcd.print(throttle);
lcd.print(" "); // 3 spaces should be enough for 3 extra digits
</code></p></li>
<li><p>Format the data with <code>snprintf()</code>:
<code>
char temp[5]; // enough room for 4 numbers and one NULL character
snprintf(temp, 5, "%4d", throttle); // %4d = 4 digits, right aligned
lcd.print(temp);
</code></p></li>
</ol>
<p>The latter method, though it is more complex and uses more resources, can be preferred because it creates a much nicer output with the numbers properly right-aligned. Also arbitrarily adding spaces after the number could overwrite things you want to keep.</p>
<p>You could also achieve a similar result doing it manually:</p>
<pre><code>if (throttle < 10) lcd.print(" "); // 0-9 add one space
if (throttle < 100) lcd.print(" "); // 0-99 add one space
if (throttle < 1000) lcd.print(" "); // 0-999 add one space
lcd.print(throttle);
</code></pre>
<p>Just like with cats, there's many ways to skin this problem...</p>
|
12979 | |arduino-ide|string|compilation-errors| | Cannot convert 'String' to 'uint8_t {aka unsigned char}' in initialization | 2015-06-29T05:31:50.917 | <p>Hey all I am trying to convert a string into a uint8_t with the following code:</p>
<pre><code>String data = "#255101987";
String tmp1 = data.substring(1, 3);
uint8_t first = (String)tmp1;
</code></pre>
<p>I am getting the error of:</p>
<blockquote>
<p>cannot convert 'String' to 'uint8_t {aka unsigned char}' in initialization</p>
</blockquote>
<p>Any help would be great as I thought adding <strong>(String)</strong> in front of the varible would solve the issue but it hasn't as you can tell.</p>
| <pre><code>uint8_t first = atoi (tmp1.substring(1, 3).c_str ());
</code></pre>
<p>Or even:</p>
<pre><code>String data = "#255101987";
uint8_t first = atoi (data.substring(1, 3).c_str ());
</code></pre>
|
12989 | |library| | Arduino C++ library syntax | 2015-06-29T14:55:17.987 | <p>I am looking at modifying the H3LI331DL I2C library posted by Seed Studio for communicating with the H3LI331DL accelerometer. The library hardcodes the address for the accelerometer in the header file. My end goal is to make the library require a slave address input argument so I can talk to 2 accelerometers on the same I2C bus. The chip has a pin that sets the LSB of its address. </p>
<p>Now onto the question. The library's .h file has the following statement:</p>
<p><code>#define H3LIS331DL_MEMS_I2C_ADDRESS 0x18//0x32</code></p>
<p>Is the 0x32 simply commented out or am I missing something here? </p>
<p>Thanks,</p>
<p>Emach </p>
| <p>It is indeed commented out. SeeedStudio is a great company but their code (including code prettifying) is pretty sloppy, and sometimes a little dumbfounding.</p>
|
13002 | |servo|gyroscope| | RC servo misbehave using arduino and MPU6050 | 2015-06-29T21:20:12.990 | <p>I am a beginner.. I am trying to control RC servo using Arduino based of data from MPU6050.
I am using library I2Cdev to communicate with gyro and to get yaw, pitch and roll. I am using example script which I have modified to control servo based on received data.</p>
<pre><code>mpu.dmpGetQuaternion(&q, fifoBuffer);
mpu.dmpGetGravity(&gravity, &q);
mpu.dmpGetYawPitchRoll(ypr, &q, &gravity);
Serial.print("ypr\t");
Serial.print(ypr[0] * 180 / M_PI);
Serial.print("\t");
Serial.print(ypr[1] * 180 / M_PI);
Serial.print("\t");
Serial.println(ypr[2] * 180 / M_PI);
pitch_angle = (ypr[1] * 180 / M_PI) + 90;
roll_angle = (ypr[2] * 180 / M_PI) + 90;
Serial.print(pitch_angle);
Serial.print("\t");
Serial.println(roll_angle);
pitchServo.write((int)(pitch_angle));
rollServo.write((int)(roll_angle));
</code></pre>
<p>Without servo being connected everything works well.
But after I plug in servo after few second being still (it seems to even follow movement of gyro) it starts to shake and then probably whole Arduino stops working (serial transmission of data stops) and Arduino has to be restarted. </p>
<pre><code>100 95
ypr 12.21 10.51 5.49
100 95
ypr 12.23 10.31 5.48
100 95
ypr 12.25 10.15 5.45
100 95
ypr 12.27 10.02 5.45
100 95
ypr -13.31 30.81 55.76
120 145
ypr 20.53 -21.36 -52.59
68 37
ypr 64.96 35.38 10.25
125 100
</code></pre>
<p>I tried to plug two 100 nF capacitors across power and ground of the servo and I tried to connect servo in to different power source than Arduino.</p>
<p><strong>EDIT:</strong>
Servo is not fixed with MPU6050 so there shouldn't be any resonance at least on the mechanical base.
Wiring is very simple:</p>
<p><img src="https://i.stack.imgur.com/BXnLN.jpg" alt="enter image description here"></p>
<p>Any idea? Thanks</p>
| <p>At the end two pull-up resistors and one capacitor solved the problem.</p>
<p>I followed instruction here:</p>
<p><a href="http://www.instructables.com/id/Brushless-Gimbal-with-Arduino/step3/Using-the-Accelerometer-and-Gyro/" rel="nofollow">http://www.instructables.com/id/Brushless-Gimbal-with-Arduino/step3/Using-the-Accelerometer-and-Gyro/</a></p>
<p>Now it works well.. Thank you all.</p>
|
13022 | |arduino-mega| | How to reset arduino Mega 2560 code automatically? | 2015-06-30T16:22:28.350 | <p>I am working on the temperature project using arduino to collect temperature. But sometimes arduino hang there so I have to unplug cord and plug it back in to restart the arduino. I do not when it is going to hang up again. So I decide to do some research on the internet but no luck for that. Here is <a href="http://sysmagazine.com/posts/189744/" rel="nofollow">the article</a> I read about resetting arduino code with watchdog timer library.(unfortunately, it only work for arduino uno) If someone has any idea how to reset arduino mega 2560 code. Please help !!</p>
| <p>I tried Gerben's suggestion with a display:</p>
<pre class="lang-C++ prettyprint-override"><code>#include <avr/wdt.h>
void setup ()
{
Serial.begin (115200);
Serial.println ();
Serial.println (F("Code starting ..."));
wdt_enable(WDTO_8S);
} // end of setup
void loop()
{
// wdt_reset();// make sure this gets called at least once every 8 seconds!
}
</code></pre>
<p>That does indeed print "Code starting ..." every 8 seconds or so.</p>
<blockquote>
<p>But sometimes arduino hang there so I have to unplug cord and plug it back in to restart the arduino. </p>
</blockquote>
<p>You are better off working out <strong>why</strong>. There is probably a bug. Fix the bug rather than just restarting the Arduino. </p>
|
13029 | |shields|prototype| | How to directly solder wires to protoshield to connect them to Arduino pins | 2015-06-30T23:58:16.597 | <p>I bought an assembled Arduino Uno protoshield version 5, similar to this:</p>
<p><img src="https://i.stack.imgur.com/oqbZo.jpg" alt="enter image description here"></p>
<p>I bought it because I would like to solder wires from Arduino IOs, and I was quite disappointed with the impossibility to do so, since the solder points are already taken by the female headers, which are not connected to anything (there are not tracks coming from then to other islands, which I find quite dumb).</p>
<p>I am considering to remove (by desoldering) the headers, so I can access the holes for soldering wires (instead of plugging them to headers), but before doing so, I ask:</p>
<blockquote>
<p>Is there a good way to solder wires so they are electrically connected to the Arduino IO pins?</p>
</blockquote>
| <p>It looks like you are missing the solder-less breadboard piece for your shield. The shield I bought came with one, and some 2 sided sticky "foam tape" to affix it to the circuit board.</p>
<p><a href="https://i.stack.imgur.com/9m6gJ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/9m6gJ.png" alt="enter image description here"></a></p>
<p>If you use the shield with the solder-less breadboard, then it would be not be feasible to stack another shield on top of it because of the height of the components and jumper wires plugged into it.</p>
<p>I tested my shield and found the same thing you did, the header pins are not connected to any of the connection points on the board. That is dumb indeed.</p>
<p>As CrossRoads mentioned in his answer, there are other options, such as screw terminal shields. They sell them for $2.43 USD on aliexpress.com <a href="https://www.aliexpress.com/item/Free-shipping-Proto-Screw-Shield-Assembled-prototype-terminal-expansion-board-for-Arduino/32382374867.html?spm=2114.search0104.3.86.acbb5c137Lx2Jl&ws_ab_test=searchweb0_0,searchweb201602_3_10152_10151_10065_10344_10068_10130_10342_10547_10343_10340_10548_10341_10696_10084_10083_10618_10139_10307_5711215_10313_10059_10534_100031_10103_10624_10623_443_10622_5711315_10621_10620_5722415,searchweb201603_37,ppcSwitch_5&algo_expid=ec60efcb-f288-4925-ac2c-2672760191ae-12&algo_pvid=ec60efcb-f288-4925-ac2c-2672760191ae&transAbTest=ae803_4&priceBeautifyAB=0" rel="nofollow noreferrer">Screw Terminal Shield</a>.</p>
|
13037 | |arduino-uno|sensors| | Velocity from Sensor Data - Best Approach? | 2015-07-01T03:44:50.293 | <p>I am attempting to develop a control system based upon rocket velocity. My first step is attempting to properly filter my sensor data in order to calculate velocity. </p>
<p>What is the best approach to get accurate, smooth, and fast data to my control logic? </p>
<p>Would I benefit from combining accelerometer and barometric data? If so, how?</p>
<hr>
<p>Background:</p>
<p>I am currently only using a BMP180 barometer to get altitude and then calculating velocity from the last altitude measurement. I am operating the BMP180 on ultra low power to increase the sample rate, but that comes at a cost of a RMS noise of around 0.5 meters.</p>
<p>Using 1D Kalman filtering I can get it smoothed out somewhat (tried on both velocity and altitude), but it is still not anywhere near as smooth as I need for my control system. It also lags behind the data far too much when I get it smoothed.</p>
<p>I have attached an example of what I have done with Kalman filtering. The original data is from a Featherweight Raven altimeter. I used the reported altitude data to calculate velocity (standard deltX/deltT) for each iteration, filtered it, and compared it with the Raven's own calculated velocity from it's accelerometer. The altitude data is at 20 Hz which is about what I am achieving with my Arduino setup right now.</p>
<p><img src="https://i.stack.imgur.com/FVwp5.png" alt="Kalman Filtering Result"></p>
<p>Thanks!</p>
| <p>You can use Excel to smooth out data and do graphs if you need to. That's what I use myself. Easiest way is to create a table and type formula to make average from range of numbers, smoother data needs a bigger range of numbers.</p>
|
13038 | |arduino-due|flash|eeprom|eepromex| | How to read/write variables persistenly on Arduino Due (no EEPROM/shield)? | 2015-07-01T05:43:28.267 | <p>I am relatively new to Arduino and I am currently writing some code to control a relay board. The on/off times are provided by the user at run-time and should be stored persistently (EEPROM or flash) in case of power-down.</p>
<p>On my Uno I worked with the EEPROMex library and that worked well. Now I have a Due which doesnt have any EEPROM and I am struggling how to store variables persistently. Specifically, I dont know how to access whatever I wrote to the flash memory previously. In the example below the content of test[] is obviously overwritten on every restart.</p>
<pre><code>PROGMEM int test[] = {1, 2, 3, 123, 23};
void test()
{
Serial.println((long)test);
for (int i = 0; i < 5; i++)
{
Serial.println(test[i]++);
}
}
</code></pre>
<p>I noticed that the address does not change during re-starts, so I I tried reading/writing beyond index 4. This out-of-bounds read/write worked, I guess since I am anyway not storing anything else. Interestingly even this memory which is out of the array is overwritten on power-up.</p>
<p>So: How do I store on unser input data (variables) persistenly on an Arduino due without using any shields?</p>
| <p>This library called DueFlashStorage was created by Sebnil and is in the Arduino Library Database Tool!</p>
<p>It basically takes the EEPROM functionality and applies it to the Flash storage on the DUE. The only drawback is that the flash memory gets erased every time you upload a new (or new version of a) sketch.</p>
<p>For my application that works but for other applications that might not be what you want!</p>
<p><a href="https://github.com/sebnil/DueFlashStorage" rel="nofollow noreferrer">Click here to go to the GitHub for it called DueFlashStorage</a></p>
|
13041 | |arduino-uno| | Why is this returning the wrong answer? | 2015-07-01T10:17:42.453 | <p>Why does this print output -3? xpos can be any value.</p>
<pre><code>void loop() {
xPos = analogRead(xPin);
yPos = analogRead(yPin);
pwm = xPos*(255/1023);
Serial.println(pwm);
}
</code></pre>
| <p>The previous answer correctly suggested writing</p>
<pre><code>pwm = xPos*(255.0f/1023.0f);
</code></pre>
<p>in place of the original form <code>pwm = xPos*(255/1023);</code>. But because 255/1023 - 1/4 = -1/1364 which is fairly small (ie it differs by 1 part in 1364), just saying</p>
<pre><code>pwm = xPos/4;
</code></pre>
<p>will usually give the correct result or nearly so. </p>
<p>Note, the following python program shows that this result is exact 514 times as xPos ranges from 0 to 1023, and is one too large 510 times, which for many processes being controlled by PWM signals is close enough.</p>
<pre><code>#!/usr/bin/env python
c = [0]*8
for i in range(1024):
vf = int(i*255.0/1023.0)
vi = i/4
d = vi-vf
c[d+3] += 1
#print '{:5} {:5} {:5} {:5}'.format(i, d, vi, vf)
print c
</code></pre>
|
13043 | |serial|arduino-mega|memory-usage| | Serial3.available loop issue | 2015-07-01T11:30:11.463 | <p>I am trying to read information coming from an Atlas Scientific FLO30 chip.</p>
<p>The following code works fine in an individual sketch: </p>
<pre><code>String inputstring = ""; //a string to hold incoming data from the PC
String sensorstring = ""; //a string to hold the data from the Atlas Scientific product
String LPM="";
float LPM_INT;
boolean input_stringcomplete = false; //have we received all the data from the PC
boolean sensor_stringcomplete = false; //have we received all the data from the Atlas Scientific product
#define CIRC_PUMP_PIN 10 // circulation pump pin - high when on, low when off
unsigned long previousMillis = 0; // will store last time LED was updated
// constants won't change :
const long interval = 1000;
void setup(){ //set up the hardware
Serial.begin(9600); //set baud rate for the hardware serial port_0 to 9600
Serial3.begin(38400); //set baud rate for software serial port_3 to 9600
inputstring.reserve(5); //set aside some bytes for receiving data from the PC
sensorstring.reserve(30); //set aside some bytes for receiving data from Atlas Scientific product
pinMode(CIRC_PUMP_PIN,OUTPUT);
digitalWrite(CIRC_PUMP_PIN,HIGH);
void loop(){
unsigned long currentMillis = millis();
if(currentMillis - previousMillis >= interval) {
// save the last time you blinked the LED
previousMillis = currentMillis;
if(Serial3.available()>0){
while(sensor_stringcomplete==false){
char inchar = (char)Serial3.read(); //get the char we just received
sensorstring += inchar; //add it to the inputString
Serial.println("adding to string");
if(inchar == '\r') {sensor_stringcomplete = true;} //if the incoming character is a <CR>, set the flag
}
}
if (sensor_stringcomplete){ //if a string from the Atlas Scientific product has been received in its entierty
Serial.println(sensorstring); //send that string to to the PC's serial monitor
byte n = sensorstring.length();
LPM = sensorstring.substring(n-8,n);
Serial.print("This is the extracted part ");
Serial.println(LPM);
LPM_INT=LPM.toFloat();
Serial.print("Now in float ");
Serial.println(LPM_INT);
LPM="";
sensorstring = ""; //clear the string:
sensor_stringcomplete = false; //reset the flag used to tell if we have received a completed string from the Atlas Scientific product
}
if(sensor_stringcomplete==false){
Serial.println("Skipping");
}
}
}
</code></pre>
<p>however when I try to integrate the code with another master sketch, the Arduino seems to jam or lockup when it enters the following part of the code, which is called periodically from the main void loop():</p>
<pre><code> if(Serial3.available()>0){
while(sensor_stringcomplete==false){
char inchar = (char)Serial3.read(); //get the char we just received
sensorstring += inchar; //add it to the inputString
Serial.println("adding to string");
if(inchar == '\r') {sensor_stringcomplete = true;} //if the incoming character is a <CR>, set the flag
}
}
</code></pre>
<p>All the code is the same and I do not understand why the Arduino locks up. I intially thought it was a problem with memory as the master code is singificantly bigger but the line "sensorstring = ""; " and "sensorstring.reserve(30) " should take care of this? Besides it cannot even get one reading from the sensor.</p>
<p>Can anyone give insight as to why this might be?</p>
| <p>Firstly, don't use String. It's wasteful of memory and the dynamic aspects of it don't sit well on a tiny resource-starved 8-bit microcontroller.</p>
<p>Secondly, your method of reading from the serial is flawed right from the start.</p>
<pre><code>if(Serial3.available()>0){
</code></pre>
<p>... If there is at least 1 character available ...</p>
<pre><code>while(sensor_stringcomplete==false){
char inchar = (char)Serial3.read(); //get the char we just received
sensorstring += inchar; //add it to the inputString
Serial.println("adding to string");
if(inchar == '\r') {sensor_stringcomplete = true;} //if the incoming character is a <CR>, set the flag
}
</code></pre>
<p>... read characters until I get the end of string character regardless of if those characters are even available.</p>
<p>In order to read the data from the serial port you have to ensure that the data is actually available. Just waiting for the first character to arrive and then reading (much faster than the serial is able to receive) other characters is doomed to failure.</p>
<p>I have discussed this at great length in a blog article, including how to perform non-blocking string reads that will not interfere with the rest of your program: <a href="http://hacking.majenko.co.uk/reading-serial-on-the-arduino" rel="nofollow">http://hacking.majenko.co.uk/reading-serial-on-the-arduino</a></p>
<p>It even mentions your specific situation since it is something that is so commonly done wrong.</p>
|
13047 | |arduino-uno| | A question about the possible limits of an Arduino Uno | 2015-07-01T17:21:29.107 | <p>I've searched the web but could not find a straightforward answer to my query.</p>
<p>I am building a control board for one of my models and this time have decided to also include a computer interface, so I have incorporated an Arduino Uno into my project instead of just analog circuits. I'm not an electronics expert of any sort but I manage by applying basic logic and a lot of trial and error.</p>
<p>Anyway, I have a single Arduino. It is operating the following:</p>
<p>An LCD display,
a 4 button operation panel I made using an LS148 ic,
an L293 operating 2 small motors,
a servo,
a dark sensor,
a temperature sensor,
and it also does serial communication.</p>
<p>Everything is working great, but slow (or so it appears to me).</p>
<p>If i push a button it takes the board about a second to pick up on the signal while an external LED indicator shows the circuit using the LS148 is working as it should. (I basically chained the 1-4 inputs and checking the truth table on the board to determine which button was pressed). Or pick up on a signal sent from the dark sensor for example. It appears as if the whole code in the Arduino runs at a cycle of once per second. Also sending instructions from the computer.</p>
<p>When I disable the LCD code everything works fast(er) and so goes when I remove other parts. So my question is, have I overloaded it?</p>
<p>I am on the verge of ordering another board (which I am going to do anyway), but in this case it is purely due to my belief that if I connect the LCD with the whole display code onto one board and the rest of the sensors and chips to another it will solve my problem.</p>
<p>I haven't figured out yet if it's possible to link the two boards or how to do that, but once I'll get to that bridge I'll cross it as well.</p>
<p>Thanks for your advice.</p>
| <p>A lot of Arduino code is written either generally inefficiently, or written in completely the wrong way.</p>
<p>For instance, take the LCD code. Commands have to be sent at the right speed with the proper delays in there for things to happen. LCDs are actually quite slow devices to communicate with, and as a result the LCD code has a large number of delays in it.</p>
<p>Nothing else can happen while there's a delay() running.</p>
<p>Many other things will introduce their own delays. Put them all together and you have a slow system.</p>
<p>No, you're not overloading it, you're slowing it down on purpose, and all those small slow-downs add up to one big grind.</p>
<p>There are other ways of doing these things, of course, which are far more friendly to the chip - things that don't require delays of any form.</p>
<p>For a start there is the millis() function which tells you the time. Using that to know when to do things, instead of sitting waiting for them to happen, allows you to do so much more at once.</p>
<p>It's like boiling an egg. Do you put the egg in boiling water and sit there staring at it for 3 minutes (or however long you like your egg cooking), or do you set the timer on your oven to alert you in 3 minutes time so you can go and do the ironing while the egg is boiling?</p>
<p>It's the same with Arduino programming. Note the time, then check that time against the current time to see if the required time has passed.</p>
<p>Of course, with things like the LCD library, changing it to work that way would be quite a lot of effort.</p>
<p>There are also hardware timers. These allow you to run small snippets of code at regular periods. Great for managing things like servos or other motors where you only want to be changing the state or speed of them say 10 times per second. Instead of updating them all the time, just set a desired speed / position variable and let the timer interrupt update the actual motor at a lower rate.</p>
<p>There are two key phrases to take away here:</p>
<ul>
<li>Non-blocking. That is basically writing routines that never wait for something to complete, but can check to see if it's time for something to happen.</li>
<li>Asynchronous programming. This is using things like timers to make things happen "outside" your main loop.</li>
</ul>
|
13055 | |arduino-leonardo|avr|avrdude|atmega32u4| | Remove Bootloader on Arduinos | 2015-07-01T22:23:50.500 | <p>I am trying to move from arduinos to AVR C. Would somebody know how to remove the arduino bootloader from the microcontroller? Is there a different process for the different atmega microcontrollers like the 32u4, 328, or 2560?</p>
<p>Thanks.</p>
| <p>You don't "remove" the bootloader, you just ignore it. When you program your new code with the hardware programmer of your choice it will just overwrite the bootloader code with your software's startup code.</p>
|
13062 | |interrupt|attiny|softwareserial|sleep| | Attiny45 wake by Software Serial | 2015-07-02T09:35:04.670 | <p>I would like to wake Attiny45 from sleep by Serial communication. RX is connected to pin 7 (D2). When I try to use PCINT0_vect routine, I get an error "multiple definition of `__vector_2'" so it looks like Software Serial already uses "ISR (PCINT0_vect)" and pin change interrupt.</p>
<p>So my question is, will incomming communication wake Attiny from sleep?</p>
<p>Is there a possibility to change CLKPR when Attiny starts receiving? For example I set clock divider to 256 for the majority of time and when it starts receiving it changes back to 1.</p>
<p>I was thinking of something like this:</p>
<pre><code>void loop() {
if (SWSerial.available()>0) {
noInterrupts ();
CLKPR = bit (CLKPCE);
CLKPR = clock_div_1;
interrupts ();
}
//other code here
}
</code></pre>
<p>I don't mind loosing some bytes, but I need to low Idle current as much as possible.
Thank you.</p>
| <h1>Question #1: Can a change on pin 7 wake from sleep?</h1>
<p>Yes. The lowest power mode for this chip is <code>Power-down</code>, and you can wake from this state with a pin change interrupt. Assuming that the soft-serial code you are using already enables interrupts on the pin for its own purposes, then you should just be able to sleep and the part will wake on the next pin generated interrupt.</p>
<p>Depending on what compiler/libraries you are using, something like this...</p>
<pre><code>include <avr/sleep.h>
...
set_sleep_mode(SLEEP_MODE_PWR_DOWN);
sleep_enable();
sleep_cpu();
//We will only reach this line after an interrupt has occured
</code></pre>
<p>...should work. Note that an interrupt when waking from sleep takes longer than when already running, so you'll need to check your soft serial library to see if it will possibly garble the first bit received- it will depend on how they do their timing.</p>
<p>If you really want the lowest power possible, you could write your own soft serial code that drops the processor to idle in between serial bit transitions. Depending on how much time you will be spending actually receiving data this could drop overall power consumption dramatically.</p>
<p>For low baud rates, I could imagine writing serial receive code that woke on an interrupt from the start bit, and used the timer running at a very low clock speed to wake up in the middle of each data bit and very quickly sample and shift the bit in before going idle again. Done right, this could dramatically drop the power used while receiving.</p>
<h1>Question #2: Is there a possibility to change CLKPR when Attiny starts receiving?</h1>
<p>Yes. You can change the prescaler any time, but note that...</p>
<ol>
<li><p>The clock is not running at all during <code>power-down</code> mode, so there is no reason to scale back before going to sleep - it will just mean that it takes you longer to wake up when a change happens.</p>
</li>
<li><p>Sometimes scaling back the clock can actually use more power, especially when sleeping is envolved. A processor running 1/2 as fast uses more than 1/2 as much power, so it is often more power efficient to wake up at full speed, do what you have to do as fast as possible, and then get back to sleep.</p>
</li>
</ol>
<p>The best option for you will depend on factors like how often will you be receiving data compared to waiting for data, and how much work you wan to put into getting optimal power usage. This chip can be <em>extremely</em> power efficient, but it can take work to take advantage of it.</p>
|
13064 | |arduino-uno|input| | Digital pin input stays high after receiving a high signal | 2015-07-02T12:50:00.157 | <p>I don't know why but when a pin set to input mode receives a high signal, then a low signal, it stays high for a seemingly random amount of time.</p>
<pre class="lang-C++ prettyprint-override"><code>#include <LiquidCrystal.h>
LiquidCrystal lcd(7, 6, 5, 4, 3, 2);
int thermPin = A5;
int relayPin = 9;
int upButton = 10;
int downButton = 11;
int rawVoltage;
float mv;
float desiredTemp = 20.5;
float currentTemp = 20;
long newSetTime = millis();
long oldSetTime = newSetTime;
long newUpPushTime = millis();
long newDownPushTime = millis();
long oldUpPushTime = millis();
long oldDownPushTime = millis();
int mainDelay = 600;
int flashDelay = 600;
boolean isSetting = true;
void drawCurrentTemp(){
lcd.setCursor(0, 1);
lcd.print(currentTemp);
}
void drawDesiredTemp(){
lcd.setCursor(12, 1);
lcd.print(desiredTemp);
}
void drawMainScreen(){
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("TEMP");
lcd.setCursor(12, 0);
lcd.print("SET");
drawCurrentTemp();
drawDesiredTemp();
}
String setString = "SET";
void flashSet(){
if(newSetTime - oldSetTime > flashDelay) {
if(setString == "SET"){
setString = " ";
}else{
setString = "SET";
}
lcd.setCursor(12, 0);
lcd.print(setString);
oldSetTime = millis();
}
}
void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
lcd.begin(16, 2);
lcd.clear();
pinMode(relayPin, OUTPUT);
pinMode(upButton, INPUT);
pinMode(downButton, INPUT);
drawMainScreen();
}
void checkInput(){
if(digitalRead(upButton) == HIGH){
newUpPushTime = millis();
} else {
oldUpPushTime = millis();
}
if(digitalRead(downButton) == HIGH){
newDownPushTime = millis();
} else {
oldDownPushTime = millis();
}
long upButtonTimePushed = newUpPushTime - oldUpPushTime;
long downButtonTimePushed = newDownPushTime - oldDownPushTime;
if(upButtonTimePushed > 1000 && downButtonTimePushed > 1000) {
oldDownPushTime = millis();
oldUpPushTime = millis();
if(!isSetting){
isSetting = true;
} else {
isSetting = false;
drawMainScreen();
}
}
if(isSetting){
if(digitalRead(upButton) == HIGH) {
desiredTemp +=0.5;
} else if(digitalRead(downButton) == HIGH) {
desiredTemp -=0.5;
}
drawDesiredTemp();
}
}
void loop() {
newSetTime = millis();
if(isSetting) {
flashSet();
}
checkInput();
Serial.println(digitalRead(upButton));
}
</code></pre>
| <p>I ran across this post and thought that a more in depth explanation should be given on why when using digital inputs that more times than not you will need to use the pull-up resistors.</p>
<p>When you define one of the pins to be a input the chip measures the voltage on the pins, if the voltage measures more than half of the VCC voltage the input is off. What happens if you don't use a Pull-up Resistor the chip will measure a seemingly random voltage. This is because of interference from other electronics, radio waves etc.</p>
<p>So what happens when you use a high resistance Resistor (10 - 100 ohms) it forces the voltage to remain high if the pin is not grounded since there is voltage being applied. But when you ground the pin using a Button or whatever the pin is kept under the halfway mark around 0V.</p>
<p>As you mentioned using the code:</p>
<pre><code>pinMode(PIN, INPUT_PULLUP);
</code></pre>
<p>enables the internal Pull-Up Resistors in the chip by setting the Pin to a High state like you would defining it as a output. The code above is a newer way of writing:</p>
<pre><code>pinMode(PIN, INPUT);
digitalWrite(PIN, HIGH);
</code></pre>
<p>Now there is another reason for seemingly random input signals, which is called "Button Bounce". What happens here is when a User presses the Button there might be a very small time that the Button actually connects then disconnects then finally reconnects. This is because of when the contacts of the Switch come together sometimes they don't connect perfectly, one side of the Switch might connect then be disconnected as the connecting plate levels out before finally connecting as it should.</p>
<p>Below is a Snapshot I found from <a href="http://www.gammon.com.au" rel="nofollow noreferrer">http://www.gammon.com.au</a>, it shows a bounce from a Osillicope showing the actual Button Bounce:</p>
<p><a href="https://i.stack.imgur.com/mR2Vz.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/mR2Vz.png" alt="Button Bounce"></a></p>
<p>To make sure that the user is actually pressing the button use a delay and recheck the Button again to see if it is still pressed. I find that a 500 - 700 microsecond delay works great. I provided a quick example on how to catch a Button Bounce (<a href="https://www.arduino.cc" rel="nofollow noreferrer">https://www.arduino.cc</a>):</p>
<pre><code>// constants won't change. They're used here to
// set pin numbers:
const int buttonPin = 2; // the number of the pushbutton pin
const int ledPin = 13; // the number of the LED pin
// Variables will change:
int ledState = HIGH; // the current state of the output pin
int buttonState; // the current reading from the input pin
int lastButtonState = LOW; // the previous reading from the input pin
// the following variables are long's because the time, measured in miliseconds,
// will quickly become a bigger number than can be stored in an int.
long lastDebounceTime = 0; // the last time the output pin was toggled
long debounceDelay = 50; // the debounce time; increase if the output flickers
void setup() {
pinMode(buttonPin, INPUT);
pinMode(ledPin, OUTPUT);
// set initial LED state
digitalWrite(ledPin, ledState);
}
void loop() {
// read the state of the switch into a local variable:
int reading = digitalRead(buttonPin);
// check to see if you just pressed the button
// (i.e. the input went from LOW to HIGH), and you've waited
// long enough since the last press to ignore any noise:
// If the switch changed, due to noise or pressing:
if (reading != lastButtonState) {
// reset the debouncing timer
lastDebounceTime = millis();
}
if ((millis() - lastDebounceTime) > debounceDelay) {
// whatever the reading is at, it's been there for longer
// than the debounce delay, so take it as the actual current state:
// if the button state has changed:
if (reading != buttonState) {
buttonState = reading;
// only toggle the LED if the new button state is HIGH
if (buttonState == HIGH) {
ledState = !ledState;
}
}
}
// set the LED:
digitalWrite(ledPin, ledState);
// save the reading. Next time through the loop,
// it'll be the lastButtonState:
lastButtonState = reading;
}
</code></pre>
<p>I hope that this explanation will help others out saving them from banging their heads against the wall trying to figure out where these phantom signals are coming from.</p>
|
13095 | |arduino-uno|arduino-ide| | Arduino sketch behaves differently depending on version of Arduino IDE | 2015-07-03T07:18:30.900 | <p>I am assisting some friends on an Arduino Uno project, and we've noticed that when using some earlier versions of the Arduino IDE (In this case 1.0.5), the sketch behaves as desired. However, when using 1.6.5, the program behaves differently. The sketch in question is here:</p>
<p><a href="https://github.com/CymaSpace/Programs---Sketches/tree/master/Tim%20Gorbunov/a3%20with%20monosetting/a3" rel="nofollow">https://github.com/CymaSpace/Programs---Sketches/tree/master/Tim%20Gorbunov/a3%20with%20monosetting/a3</a></p>
<p>I have noticed that when enabling verbose compilation output, the size of the compiled binary is different between the two different IDE versions. There are also some warnings in the older IDE that are not present in the newer version. There is at least one other version before 1.6.5 that is behaving the same way as 1.0.5 (it's a later version but at the moment I don't know which, I will see if I can find out and post it here later).</p>
<p>Any idea why the two sketches might be behaving differently and how to go about troubleshooting the problem? This occurred on both a windows and mac computer. Thanks!</p>
| <blockquote>
<p>There are also some warnings in the older IDE that are not present in
the newer version.</p>
</blockquote>
<p>It is a <strong>huge</strong> mistake to disregards those warnings, especially:</p>
<blockquote>
<p>warning: array subscript is above array bounds</p>
</blockquote>
<p>You declared an array <code>int useColor[2]</code>. Its length is 2 and its indices
can be either 0 or 1. Yet you are using <code>useColor[2]</code>, which is out of
bounds and likely to corrupt memory.</p>
<p>From the language point of view, this is called <em>undefined behavior</em>,
which means that <em>anything</em> can happen. In particular, it could very
well happen that the program behaves as you expect... which seems to be
the case with IDE 1.0.5. Simply changing the compiler version, or event
the compiler settings, can change the behavior.</p>
|
13099 | |servo| | Outlet switcher using servo motor | 2015-07-03T09:03:21.937 | <p>I am building a small-scale watering system to water my plants, controlled by Arduino. I have designed most of the project except for how to switch water between multiple pipes.</p>
<p>A little more background:</p>
<p>I want to be able to use a servo motor to control the amount of water that is sent to each plant (based on pot size and plant type). The motor needs to be able to switch input (a 1/2 inch pipe carrying water) to a set of outputs (similarly sized pipes all going to different plants). I am not able to find something off the shelf that does this. So, I am about to 3D print something. Is there something available that I can use instead?</p>
| <p>As JRobert mentioned in a comment, you could use a <a href="http://www.ebay.com/sch/i.html?_odkw=solenoid+valve&_osacat=0&_from=R40&_trksid=p2045573.m570.l1313.TR0.TRC0.H0.TRS0&_nkw=solenoid+valve&_sacat=0" rel="nofollow">solenoid valve</a>, some of which you can get for about $5.</p>
<p>If you want to water one line at a time, get Normally Closed, one per line. Naturally, since most of them are 12v DC, you can't directly power them from your Arduino. You'll need some power transistors or some relays, and a 12v supply capable of steadily powering the solenoid.</p>
|
13105 | |visualstudio| | How do I add additional compiler switches in Visual Studio | 2015-07-03T14:50:50.280 | <p>Using Visual Studio to program my Arduino. I want to add additional compiler switches and include paths.</p>
<p>How can this be done?</p>
| <p>Use the ExtraFlags in the project properties. The flags can be specified for the currently selected configuration or for all builds of the current project.</p>
<p>The feature was released in the 15.06 version of the <a href="http://www.visualmicro.com" rel="nofollow">Visual Micro</a> Arduino plugin for Visual Studio.</p>
<p>This <a href="http://www.visualmicro.com/page/User-Guide.aspx?doc=Project-Properties-Reference.html" rel="nofollow">guide</a> shows how to access the project properties</p>
|
13107 | |arduino-mega| | Is it possible to see a graphical view of digital and analog pin values? | 2015-07-03T14:58:34.223 | <p>Using Visual Studio for my Arduino project I am struggling to know the states of various pins during operation.</p>
<p>I do use the Visual Micro debugger but I don't want to have to set a watch for every pin.</p>
<p>How can this be done easily?</p>
| <p>Visual Micro provides this for you if you have the debug module enabled. It also optionally shows analog, memory and i2c. Read more about <a href="http://www.visualmicro.com/page/Debugging-for-Arduino.aspx" rel="nofollow noreferrer">Arduino debug and the digital pin viewer</a></p>
<p><img src="https://i.stack.imgur.com/TsFgI.png" alt="enter image description here"></p>
|
13114 | |arduino-uno|programming|rfid| | rfid_default_keys check with RC522 | 2015-07-03T18:16:50.363 | <p>I just received a RC522 board and since i am new to RFID, I tried out some examples from <a href="https://github.com/miguelbalboa/rfid" rel="nofollow noreferrer" title="Arduino RFID Library for MFRC522">"Arduino RFID Library for MFRC522"</a>. Here's one of them
<strong>rfid_default_keys</strong></p>
<pre><code>/*
* ----------------------------------------------------------------------------
* This is a MFRC522 library example; see https://github.com/miguelbalboa/rfid
* for further details and other examples.
*
* NOTE: The library file MFRC522.h has a lot of useful info. Please read it.
*
* Released into the public domain.
* ----------------------------------------------------------------------------
* Example sketch/program which will try the most used default keys listed in
* https://code.google.com/p/mfcuk/wiki/MifareClassicDefaultKeys to dump the
* block 0 of a MIFARE RFID card using a RFID-RC522 reader.
*
* Typical pin layout used:
* -----------------------------------------------------------------------------------------
* MFRC522 Arduino Arduino Arduino Arduino Arduino
* Reader/PCD Uno Mega Nano v3 Leonardo/Micro Pro Micro
* Signal Pin Pin Pin Pin Pin Pin
* -----------------------------------------------------------------------------------------
* RST/Reset RST 9 5 D9 RESET/ICSP-5 RST
* SPI SS SDA(SS) 10 53 D10 10 10
* SPI MOSI MOSI 11 / ICSP-4 51 D11 ICSP-4 16
* SPI MISO MISO 12 / ICSP-1 50 D12 ICSP-1 14
* SPI SCK SCK 13 / ICSP-3 52 D13 ICSP-3 15
*
*/
#include <SPI.h>
#include <MFRC522.h>
#define RST_PIN 9 // Configurable, see typical pin layout above
#define SS_PIN 10 // Configurable, see typical pin layout above
MFRC522 mfrc522(SS_PIN, RST_PIN); // Create MFRC522 instance.
// Number of known default keys (hard-coded)
// NOTE: Synchronize the NR_KNOWN_KEYS define with the defaultKeys[] array
#define NR_KNOWN_KEYS 8
// Known keys, see: https://code.google.com/p/mfcuk/wiki/MifareClassicDefaultKeys
byte knownKeys[NR_KNOWN_KEYS][MFRC522::MF_KEY_SIZE] = {
{0xff, 0xff, 0xff, 0xff, 0xff, 0xff}, // FF FF FF FF FF FF = factory default
{0xa0, 0xa1, 0xa2, 0xa3, 0xa4, 0xa5}, // A0 A1 A2 A3 A4 A5
{0xb0, 0xb1, 0xb2, 0xb3, 0xb4, 0xb5}, // B0 B1 B2 B3 B4 B5
{0x4d, 0x3a, 0x99, 0xc3, 0x51, 0xdd}, // 4D 3A 99 C3 51 DD
{0x1a, 0x98, 0x2c, 0x7e, 0x45, 0x9a}, // 1A 98 2C 7E 45 9A
{0xd3, 0xf7, 0xd3, 0xf7, 0xd3, 0xf7}, // D3 F7 D3 F7 D3 F7
{0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff}, // AA BB CC DD EE FF
{0x00, 0x00, 0x00, 0x00, 0x00, 0x00} // 00 00 00 00 00 00
};
/*
* Initialize.
*/
void setup() {
Serial.begin(9600); // Initialize serial communications with the PC
while (!Serial); // Do nothing if no serial port is opened (added for Arduinos based on ATMEGA32U4)
SPI.begin(); // Init SPI bus
mfrc522.PCD_Init(); // Init MFRC522 card
Serial.println(F("Try the most used default keys to print block 0 of a MIFARE PICC."));
}
/*
* Helper routine to dump a byte array as hex values to Serial.
*/
void dump_byte_array(byte *buffer, byte bufferSize) {
for (byte i = 0; i < bufferSize; i++) {
Serial.print(buffer[i] < 0x10 ? " 0" : " ");
Serial.print(buffer[i], HEX);
}
}
/*
* Try using the PICC (the tag/card) with the given key to access block 0.
* On success, it will show the key details, and dump the block data on Serial.
*
* @return true when the given key worked, false otherwise.
*/
boolean try_key(MFRC522::MIFARE_Key *key)
{
boolean result = false;
byte buffer[18];
byte block = 0;
byte status;
// Serial.println(F("Authenticating using key A..."));
status = mfrc522.PCD_Authenticate(MFRC522::PICC_CMD_MF_AUTH_KEY_A, block, key, &(mfrc522.uid));
if (status != MFRC522::STATUS_OK) {
// Serial.print(F("PCD_Authenticate() failed: "));
// Serial.println(mfrc522.GetStatusCodeName(status));
return false;
}
// Read block
byte byteCount = sizeof(buffer);
status = mfrc522.MIFARE_Read(block, buffer, &byteCount);
if (status != MFRC522::STATUS_OK) {
// Serial.print(F("MIFARE_Read() failed: "));
// Serial.println(mfrc522.GetStatusCodeName(status));
}
else {
// Successful read
result = true;
Serial.print(F("Success with key:"));
dump_byte_array((*key).keyByte, MFRC522::MF_KEY_SIZE);
Serial.println();
// Dump block data
Serial.print(F("Block ")); Serial.print(block); Serial.print(F(":"));
dump_byte_array(buffer, 16);
Serial.println();
}
Serial.println();
mfrc522.PICC_HaltA(); // Halt PICC
mfrc522.PCD_StopCrypto1(); // Stop encryption on PCD
return result;
}
/*
* Main loop.
*/
void loop() {
// Look for new cards
if ( ! mfrc522.PICC_IsNewCardPresent())
return;
// Select one of the cards
if ( ! mfrc522.PICC_ReadCardSerial())
return;
// Show some details of the PICC (that is: the tag/card)
Serial.print(F("Card UID:"));
dump_byte_array(mfrc522.uid.uidByte, mfrc522.uid.size);
Serial.println();
Serial.print(F("PICC type: "));
byte piccType = mfrc522.PICC_GetType(mfrc522.uid.sak);
Serial.println(mfrc522.PICC_GetTypeName(piccType));
// Try the known default keys
MFRC522::MIFARE_Key key;
for (byte k = 0; k < NR_KNOWN_KEYS; k++) {
// Copy the known key into the MIFARE_Key structure
for (byte i = 0; i < MFRC522::MF_KEY_SIZE; i++) {
key.keyByte[i] = knownKeys[k][i];
}
// Try the key
if (try_key(&key)) {
// Found and reported on the key and block,
// no need to try other keys for this PICC
break;
}
}
}
</code></pre>
<p>So i modified the code to see exactly what is happening there and here is my output:
<img src="https://i.stack.imgur.com/LuWoT.png" alt="my output"></p>
<p>Everything looks fine, right ?
So i tried to modify it again by adding some more stuff to the <em>knownKeys</em> array
but it looks like that only the first key is used in the actual authentication.
Here's an output for the same card but i moved <code>{0xff, 0xff, 0xff, 0xff, 0xff, 0xff}, // FF FF FF FF FF FF = factory default</code> to the end of that array.
<img src="https://i.stack.imgur.com/FocJM.png" alt="enter image description here"></p>
<p>So.. as you can see even if it used the right key, nothing happened.
For the solution i tried few things but without a success. Thanks in advance for answering.</p>
| <p>Based on some experimenting, I believe the 1st key is skipped for one of two reasons:</p>
<ol>
<li>If you follow the code flow, in <code>loop()</code>, <code>PICC_IsNewCardPresent()</code> and <code>PICC_ReadCardSerial()</code> called. If a "new" card/tag is present, then <code>try_key()</code> is called which calls <code>PICC_IsNewCardPresent()</code> [and <code>PICC_ReadCardSerial()</code>] again. Since the card/tag is not "new", <code>PICC_IsNewCardPresent()</code> returns false.
or</li>
<li>It appears that if the correct key is the default of all 0xFF's, then a call to <code>PCD_Authenticate()</code> will fail.</li>
</ol>
<p>I'm still working a new version of rfid_default_keys to fix the problem.</p>
|
13121 | |arduino-uno|motor|voltage-level| | DIY Watering - Required components | 2015-07-03T22:00:37.853 | <p>I am looking as a first project after some simple project kits, to make a watering system for my indoor plants. I have seen a few projects on instructables, so I went to look for components. I am not sure how to power the pump from the Arduino.</p>
<p>My idea is the following:</p>
<p>A bucket of water with a water pump inside. An irrigation system linked to the pump, which then goes to all the plants. The pump linked to arduino which turns it on and off based on a timer.</p>
<p>The components that I will be using are an Arduino uno and:</p>
<ul>
<li><a href="http://www.ebay.co.uk/itm/351304928817" rel="nofollow">DV12 subversive pump</a></li>
<li><a href="http://www.ebay.co.uk/itm/271401027990" rel="nofollow">Irrigation watering kit</a></li>
</ul>
<p>Also I guess I will need some tube to connect the pump to the watering kit.</p>
<p>I am not sure how to connect and power the pump (12V) with the arduino. The arduino it self will be powered by a USB on a wall socket.</p>
| <p>I have some details about running motors etc. from Arduino pins at <a href="http://www.gammon.com.au/motors" rel="nofollow noreferrer">Driving motors, lights, etc. from an Arduino output pin</a>.</p>
<p>Quite possibly what would work for you is a MOSFET - as Majenko suggested - connected up like this:</p>
<p><img src="https://i.stack.imgur.com/2QDZa.png" alt="Low-side MOSFET driver"></p>
<p>In this case you connect the positive side of your 12V supply for your pump to the pump, and the MOSFET sinks current to ground, when you require the pump on.</p>
<p>Don't forget the diode D1 which prevents damage from the inductive load of the pump generating high-voltage spikes.</p>
|
13126 | |voltage-level|voltage-protection| | best way to protect a digital or analog input from 12volts | 2015-07-04T01:03:43.833 | <p>At work, I have connected an Arduino to a security key (which has a 12v power supply) in order to give us a more versatile door lock. Unfortunately, people keep removing the key pad, disconnecting the wires and re-connecting them (defective keypad I guess.) In the process, I am afraid that they will accidentally send 12v into the Vcc, ground, digital in, and/or analog in pins. What is the best way to protect my Arduino from the 12 volts? I really need a component or two that I can to my pins.</p>
<p>Edit: it is difficult for me to describe this problem without mentioning the danger to all components. Please describe ways to protect digital outputs <a href="https://arduino.stackexchange.com/questions/13150/best-way-to-protect-a-digital-output">HERE</a></p>
| <p>There are some suggestions at <a href="http://www.digikey.com/en/articles/techzone/2012/apr/protecting-inputs-in-digital-electronics" rel="nofollow noreferrer">Protecting Inputs in Digital Electronics </a>.</p>
<p><em>Amended answer</em></p>
<p>Testing of my earlier answer involving clamping diodes gave unsatisfactory results. Due to the small current flow the diodes allowed a considerable voltage to reach the input pin (like, 9 V).</p>
<p>The amended circuit below, tested with 12V input, satisfactorily keeps the Arduino input pin to 4.9 V, even with 12 V from the device. The current through R1 is around 7 mA which is what you would expect:</p>
<pre><code>I = V / R
I = 7 / 1000
I = 7 mA
</code></pre>
<p>The 1N4733A is a 5.1 V, 1 W zener diode which can therefore handle dropping 5 V at 7 mA.</p>
<p>In case you are wondering where the number 7 comes from in the calculations above:</p>
<ul>
<li>The input voltage is 12 volts</li>
<li>The desired output is 5 volts</li>
<li>Therefore we need to drop (12 - 5) volts over the resistor</li>
<li>Thus 7 volts are dropped over the resistor</li>
</ul>
<hr>
<p><img src="https://i.stack.imgur.com/SkcmD.png" alt="Input pin protection"></p>
<p>Further reference material:</p>
<ul>
<li><p><a href="http://www.ruggedcircuits.com/10-ways-to-destroy-an-arduino" rel="nofollow noreferrer">10 Ways to Destroy An Arduino</a></p></li>
<li><p><a href="http://www.thebox.myzen.co.uk/Tutorial/Protection.html" rel="nofollow noreferrer">Protection</a></p></li>
<li><p><a href="http://www.kevinmfodor.com/home/My-Blog/microcontrollerinputprotectiontechniques" rel="nofollow noreferrer">Microcontroller Input Protection Techniques</a></p></li>
</ul>
|
13131 | |reset| | can I create an on/off switch for my Arduino using the reset pin? | 2015-07-04T02:11:52.377 | <p>If i connect a switch to the reset pin, can I create an effective way of turning off the Arduino (overnight) without removing its power supply? </p>
| <p>Tests show that connecting Reset to Ground on a Uno reduces the power consumption from 47 mA to 41 mA. So it is hardly "off".</p>
<p>All that would do is stop the currently-loaded sketch running, and save a few milliamps.</p>
|
13133 | |arduino-uno|led| | Fading from color to color using for-loop FastLEDs | 2015-07-04T03:14:36.387 | <p>I'm attempting to fade a strip of ws2812 7 pixels in length. Below I am using a for loop to increment the color red. I can fade it to red (from blue) but it will do it one pixel at a time or it just stays blue, depending where I move my r for-loop to. I need it to fade from color to color all 7 LEDs at once. </p>
<p>I get no errors. </p>
<p>I don't understand the process of getting NUM_LEDS leds all into x then proceeding with my color changing. Seems like I'm grabbing one pixel, fading it to red, then another...</p>
<p>fastLeds 3.03 library, arduino 1.0.6</p>
<pre><code>#include <FastLED.h>
#define DATA_PIN 6
#define NUM_LEDS 7
#define BRIGHTNESS 45
#define COLOR_ORDER GRB
#define g 50
#define b 100
int r;
CRGB leds[NUM_LEDS];
void setup(){
FastLED.addLeds<WS2811, DATA_PIN, GRB>(leds, NUM_LEDS);
}
void loop(){
for(int x = 0; x < NUM_LEDS; x++){
delay(10);
leds[x] = CRGB(r,g,b);
}
FastLED.show();
delay(10);
//-------------------------
for(int x = 0; x < NUM_LEDS; x++){
for(int r = 0; r < 254; r++) {
</code></pre>
<p>if NUM_LEDS is holding the number 7 why can't I just do it like this below: leds[NUM_LEDS]?</p>
<pre><code> leds[x] = CRGB(r,g,b);
FastLED.show();
delay(100);
}
}
}
</code></pre>
| <p>Here is the initial 0-255 rainbow. I dunno if this is what you are trying to achieve but i took initiative from @bigjosh's answer. This just cycles thru each rgb from 0-255. @bigjosh does start red at 0-255 allowing for more for red colors.</p>
<pre><code>void loop(){
//start from red
for( int colorStep=0; colorStep <= 255; colorStep++ ) {
int r = 255;
int g = 0;
int b = colorStep;
// Now loop though each of the LEDs and set each one to the current color
for(int x = 0; x < LED_COUNT; x++){
leds[x] = CRGB(r,g,b);
}
// Display the colors we just set on the actual LEDs
delay(10);
FastLED.show();
}
//into blue
for( int colorStep=255; colorStep >= 0; colorStep-- ) {
int r = colorStep;
int g = 0;
int b = 255;
// Now loop though each of the LEDs and set each one to the current color
for(int x = 0; x < LED_COUNT; x++){
leds[x] = CRGB(r,g,b);
}
// Display the colors we just set on the actual LEDs
delay(10);
FastLED.show();
}
//start from blue
for( int colorStep=0; colorStep <= 255; colorStep++ ) {
int r = 0;
int g = colorStep;
int b = 255;
// Now loop though each of the LEDs and set each one to the current color
for(int x = 0; x < LED_COUNT; x++){
leds[x] = CRGB(r,g,b);
}
// Display the colors we just set on the actual LEDs
delay(10);
FastLED.show();
}
//into green
for( int colorStep=255; colorStep >= 0; colorStep-- ) {
int r = 0;
int g = 255;
int b = colorStep;
// Now loop though each of the LEDs and set each one to the current color
for(int x = 0; x < LED_COUNT; x++){
leds[x] = CRGB(r,g,b);
}
// Display the colors we just set on the actual LEDs
delay(wait_time);
LEDS.show();
}
//start from green
for( int colorStep=0; colorStep <= 255; colorStep++ ) {
int r = colorStep;
int g = 255;
int b = 0;
// Now loop though each of the LEDs and set each one to the current color
for(int x = 0; x < LED_COUNT; x++){
leds[x] = CRGB(r,g,b);
}
// Display the colors we just set on the actual LEDs
delay(wait_time);
LEDS.show();
}
//into yellow
for( int colorStep=255; colorStep >= 0; colorStep-- ) {
int r = 255;
int g = colorStep;
int b = 0;
// Now loop though each of the LEDs and set each one to the current color
for(int x = 0; x < LED_COUNT; x++){
leds[x] = CRGB(r,g,b);
}
// Display the colors we just set on the actual LEDs
delay(wait_time);
LEDS.show();
}
} //end main loop
</code></pre>
|
13142 | |arduino-motor-shield| | Motor Shield StepMotor | 2015-07-04T11:27:37.217 | <p><img src="https://i.stack.imgur.com/lWDH8.jpg" alt="enter image description here"></p>
<p>What the two yellow cables as you can see in the picture do not know?</p>
| <p>There are two types of stepper motors: unipolar and bipolar. Bipolars usually have four wires and unipolars have six.</p>
<blockquote>
<p><a href="https://i.stack.imgur.com/1Mi9t.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/1Mi9t.png" alt=""></a></p>
<p>--<a href="http://hobbymilling.com/wp-content/uploads/2011/05/Unipolar-stepper-motor-windings.png" rel="nofollow noreferrer">http://hobbymilling.com/wp-content/uploads/2011/05/Unipolar-stepper-motor-windings.png</a></p>
<p><img src="https://www.codeproject.com/KB/system/steppermotorcontrol/pic6.jpg" alt=""></p>
<p>--<a href="https://www.codeproject.com/KB/system/steppermotorcontrol/pic6.jpg" rel="nofollow noreferrer">https://www.codeproject.com/KB/system/steppermotorcontrol/pic6.jpg</a></p>
</blockquote>
<p>The motor shield is designed to drive a bipolar motor (4 wires) but the motor is unipolar (6 wires). As you can see in the pictures, if you ignore the middle wire of the unipolar motor, it is the exact same as a bipolar stepper motor.</p>
|
13165 | |pins| | How to read pinMode for digital pin? | 2015-07-05T14:04:55.063 | <p>Is there a way for me to read the pin mode for one of the digital pins on Arduino? In other words, can I determine whether a pin's been set to an input or output?</p>
| <p>Seems like the Arduino core is missing a function to read the pinMode(). Here is a possible implementation:</p>
<pre><code>int pinMode(uint8_t pin)
{
if (pin >= NUM_DIGITAL_PINS) return (-1);
uint8_t bit = digitalPinToBitMask(pin);
uint8_t port = digitalPinToPort(pin);
volatile uint8_t *reg = portModeRegister(port);
if (*reg & bit) return (OUTPUT);
volatile uint8_t *out = portOutputRegister(port);
return ((*out & bit) ? INPUT_PULLUP : INPUT);
}
</code></pre>
<p>It handles illegal pin numbers (return -1), and all pin modes; OUTPUT, INPUT and INPUT_PULLUP. </p>
<p>Cheers!</p>
<p>BW: I have added this as an <a href="https://github.com/arduino/Arduino/issues/4606" rel="noreferrer">issue</a> on the Arduino github repository. </p>
|
13167 | |serial|atmega328|sleep| | Put ATmega328 in very deep sleep and listen to serial? | 2015-07-05T10:46:14.083 | <p>I have investigated the sleeps options of the ATmega328, and read a few articles about it, and I would like to understand if there are more options.</p>
<p>So I would like to get as low current as possible, so that anything less that 100uA would be good - as long as I can listen to uart and interrupts for waking up.</p>
<p>I am using a custom PCB (not the UNO), with ATmega328p.</p>
<p>Setting the chip to deep sleep:</p>
<pre><code> set_sleep_mode (SLEEP_MODE_PWR_DOWN);
sleep_enable();
sleep_cpu ();
</code></pre>
<p>would not wake it up with serial communication,according to <a href="http://playground.arduino.cc/Learning/ArduinoSleepCode" rel="noreferrer">this</a>.</p>
<p>You will need to put it in <code>IDLE</code> mode, to listen to serial, but this would consume a few mA -bad.</p>
<p>I have found <a href="http://donalmorrissey.blogspot.co.il/2010/04/sleeping-arduino-part-3-wake-up-via.html" rel="noreferrer">this link</a> where you can connect in hardware the serial to the interrupt - which is dangerous so you can loose data, and moreover, I need these 2 interrupts pins.</p>
<p>I also read <a href="http://www.gammon.com.au/forum/?id=11497" rel="noreferrer">this article of Gammon</a>, where you can disable some things, so you can get IDLE sleep with much lower power - but he didn't mention how exactly you get from this:</p>
<pre><code> power_adc_disable();
power_spi_disable();
power_timer0_disable();
power_timer1_disable();
power_timer2_disable();
power_twi_disable();
</code></pre>
<p>So, bottom line, is there any option out there, to get less than 0.25mA at least, and also listen to serial port, without any hardware manipulation?
For example, waking up with <strong>long serial data</strong> input?</p>
| <p>The code below achieves what you are asking:</p>
<pre class="lang-c++ prettyprint-override"><code>#include <avr/sleep.h>
#include <avr/power.h>
const byte AWAKE_LED = 8;
const byte GREEN_LED = 9;
const unsigned long WAIT_TIME = 5000;
ISR (PCINT2_vect)
{
// handle pin change interrupt for D0 to D7 here
} // end of PCINT2_vect
void setup()
{
pinMode (GREEN_LED, OUTPUT);
pinMode (AWAKE_LED, OUTPUT);
digitalWrite (AWAKE_LED, HIGH);
Serial.begin (9600);
} // end of setup
unsigned long lastSleep;
void loop()
{
if (millis () - lastSleep >= WAIT_TIME)
{
lastSleep = millis ();
noInterrupts ();
byte old_ADCSRA = ADCSRA;
// disable ADC
ADCSRA = 0;
// pin change interrupt (example for D0)
PCMSK2 |= bit (PCINT16); // want pin 0
PCIFR |= bit (PCIF2); // clear any outstanding interrupts
PCICR |= bit (PCIE2); // enable pin change interrupts for D0 to D7
set_sleep_mode (SLEEP_MODE_PWR_DOWN);
power_adc_disable();
power_spi_disable();
power_timer0_disable();
power_timer1_disable();
power_timer2_disable();
power_twi_disable();
UCSR0B &= ~bit (RXEN0); // disable receiver
UCSR0B &= ~bit (TXEN0); // disable transmitter
sleep_enable();
digitalWrite (AWAKE_LED, LOW);
interrupts ();
sleep_cpu ();
digitalWrite (AWAKE_LED, HIGH);
sleep_disable();
power_all_enable();
ADCSRA = old_ADCSRA;
PCICR &= ~bit (PCIE2); // disable pin change interrupts for D0 to D7
UCSR0B |= bit (RXEN0); // enable receiver
UCSR0B |= bit (TXEN0); // enable transmitter
} // end of time to sleep
if (Serial.available () > 0)
{
byte flashes = Serial.read () - '0';
if (flashes > 0 && flashes < 10)
{
// flash LED x times
for (byte i = 0; i < flashes; i++)
{
digitalWrite (GREEN_LED, HIGH);
delay (200);
digitalWrite (GREEN_LED, LOW);
delay (200);
}
}
} // end of if
} // end of loop
</code></pre>
<p>I used a pin-change interrupt on the Rx pin to notice when serial data arrives. In this test the board goes to sleep if there is no activity after 5 seconds (the "awake" LED goes out). Incoming serial data causes the pin-change interrupt to wake the board. It looks for a number and flashes the "green" LED that number of times.</p>
<h2>Measured current</h2>
<p>Running at 5 V, I measured about 120 nA of current when asleep (0.120 µA). </p>
<h2>Awakening message</h2>
<p>A problem however is that the first arriving byte is lost due to the fact that the serial hardware expects a falling level on Rx (the start bit) which has already arrived by the time it is fully awake.</p>
<p>I suggest (as in geometrikal's answer) that you first send an "awake" message, and then <strong>pause</strong> for a short time. The pause is to make sure the hardware does not interpret the next byte as part of the awake message. After that it should work fine.</p>
<hr>
<p>Since this uses a pin-change interrupt no other hardware is required.</p>
<hr>
<h1>Amended version using SoftwareSerial</h1>
<p>The version below successfully processes the first byte received on serial. It does this by:</p>
<ul>
<li><p>Using SoftwareSerial which uses pin-change interrupts. The interrupt which is caused by the start bit of the first serial byte also wakes the processor.</p></li>
<li><p>Setting the fuses so that we use:</p>
<ul>
<li>Internal RC oscillator</li>
<li>BOD disabled</li>
<li>The fuses were: Low: 0xD2, High: 0xDF, Extended: 0xFF</li>
</ul></li>
</ul>
<p>Inspired by FarO in a comment, this lets the processor wake up in 6 clock cycles (750 ns). At 9600 baud each bit time is 1/9600 (104.2 µs) so the extra delay is insignificant.</p>
<pre class="lang-c++ prettyprint-override"><code>#include <avr/sleep.h>
#include <avr/power.h>
#include <SoftwareSerial.h>
const byte AWAKE_LED = 8;
const byte GREEN_LED = 9;
const unsigned long WAIT_TIME = 5000;
const byte RX_PIN = 4;
const byte TX_PIN = 5;
SoftwareSerial mySerial(RX_PIN, TX_PIN); // RX, TX
void setup()
{
pinMode (GREEN_LED, OUTPUT);
pinMode (AWAKE_LED, OUTPUT);
digitalWrite (AWAKE_LED, HIGH);
mySerial.begin(9600);
} // end of setup
unsigned long lastSleep;
void loop()
{
if (millis () - lastSleep >= WAIT_TIME)
{
lastSleep = millis ();
noInterrupts ();
byte old_ADCSRA = ADCSRA;
// disable ADC
ADCSRA = 0;
set_sleep_mode (SLEEP_MODE_PWR_DOWN);
power_adc_disable();
power_spi_disable();
power_timer0_disable();
power_timer1_disable();
power_timer2_disable();
power_twi_disable();
sleep_enable();
digitalWrite (AWAKE_LED, LOW);
interrupts ();
sleep_cpu ();
digitalWrite (AWAKE_LED, HIGH);
sleep_disable();
power_all_enable();
ADCSRA = old_ADCSRA;
} // end of time to sleep
if (mySerial.available () > 0)
{
byte flashes = mySerial.read () - '0';
if (flashes > 0 && flashes < 10)
{
// flash LED x times
for (byte i = 0; i < flashes; i++)
{
digitalWrite (GREEN_LED, HIGH);
delay (200);
digitalWrite (GREEN_LED, LOW);
delay (200);
}
}
} // end of if
} // end of loop
</code></pre>
<p>Power consumption when asleep was measured as 260 nA (0.260 µA) so that is very low consumption when not needed.</p>
<p>Note that with the fuses set like that, the processor runs at 8 MHz. Thus you need to tell the IDE about that (eg. select "Lilypad" as the board type). That way the delays and SoftwareSerial will work at the correct speed.</p>
|
13178 | |programming|c++|class| | Classes and objects: how many and which file types do I actually need to use them? | 2015-07-06T00:41:22.507 | <p>I have no previous experience with C++ or C, but know how to program C# and am learning Arduino. I just want to organize my sketches and am quite comfortable with the Arduino language even with its limitations, but I really would like to have an object-oriented approach to my Arduino programming.</p>
<p>So I have seen that you can have the following ways (not exhaustive list) to organize code:</p>
<ol>
<li>A single .ino file;</li>
<li>Multiple .ino files in the same folder (what the IDE calls and displays like "tabs");</li>
<li>An .ino file with an included .h and .cpp file in the same folder;</li>
<li>Same as above, but the files are an installed library inside Arduino program folder.</li>
</ol>
<p>I have also heard of the following ways, but have not got them working yet:</p>
<ul>
<li>Declaring a C++-style class in the same, single .ino file (have heard of, but never seen working - is that even possible?);</li>
<li><strong>[preferred approach]</strong> Including a .cpp file where a class is declared, but <em>without</em> using a .h file (would like this approach, should that work?);</li>
</ul>
<p>Note that I only want to use classes so that code is more partitioned, my applications should be very simple, only involving buttons, leds and buzzers mostly.</p>
| <p>I'm posting an answer just for completeness, after finding out and testing a way of declaring <em>and</em> implementing a class in the same .cpp file, without using a header. So, regarding the exact phrasing of my question "how many file types do I need to use classes", the present answer uses two files: one .ino with an include, setup and loop, and the .cpp containing the whole (rather minimalistic) class, representing the turning signals of a toy vehicle.</p>
<p>Blinker.ino</p>
<pre><code>#include <TurnSignals.cpp>
TurnSignals turnSignals(2, 4, 8);
void setup() { }
void loop() {
turnSignals.run();
}
</code></pre>
<p>TurnSignals.cpp</p>
<pre><code>#include "Arduino.h"
class TurnSignals
{
int
_left,
_right,
_buzzer;
const int
amberPeriod = 300,
beepInFrequency = 600,
beepOutFrequency = 500,
beepDuration = 20;
boolean
lightsOn = false;
public : TurnSignals(int leftPin, int rightPin, int buzzerPin)
{
_left = leftPin;
_right = rightPin;
_buzzer = buzzerPin;
pinMode(_left, OUTPUT);
pinMode(_right, OUTPUT);
pinMode(_buzzer, OUTPUT);
}
public : void run()
{
blinkAll();
}
void blinkAll()
{
static long lastMillis = 0;
long currentMillis = millis();
long elapsed = currentMillis - lastMillis;
if (elapsed > amberPeriod) {
if (lightsOn)
turnLightsOff();
else
turnLightsOn();
lastMillis = currentMillis;
}
}
void turnLightsOn()
{
tone(_buzzer, beepInFrequency, beepDuration);
digitalWrite(_left, HIGH);
digitalWrite(_right, HIGH);
lightsOn = true;
}
void turnLightsOff()
{
tone(_buzzer, beepOutFrequency, beepDuration);
digitalWrite(_left, LOW);
digitalWrite(_right, LOW);
lightsOn = false;
}
};
</code></pre>
|
13190 | |arduino-uno|programming| | 0 value integer does not enter If | 2015-07-06T10:00:57.103 | <p>I'm sure this is a very basic coding mistake...</p>
<p>I'm picking up a reading from A0. If the value is 0, I want the value of the serial to be written to the Serial Monitor.</p>
<p>I also want it only to write to the Serial Monitor for the first time that the value falls to 0.</p>
<p>I don't understand why, when the value for SensorValue = 0, the if is not performed.</p>
<p>This is my code:</p>
<pre><code>boolean must_print = true;
int sensorValue = 0;
// the setup routine runs once when you press reset:
void setup() {
// initialize serial communication at 9600 bits per second:
Serial.begin(9600);
}
// the loop routine runs over and over again forever:
void loop() {
// read the input on analog pin 0:
sensorValue = analogRead(A0);
if (sensorValue = 0) {
if (must_print = true)
{
must_print = false;
Serial.println(sensorValue);
}
else
must_print = true
}
delay(500); // delay in between reads for stability
}
</code></pre>
<p>Thanks!</p>
| <pre><code> if (sensorValue = 0) {
</code></pre>
<p>That assigns zero to sensorValue, which then tests false. You want:</p>
<pre><code> if (sensorValue == 0) {
</code></pre>
|
13198 | |arduino-uno|ethernet| | Sending a double message for action to occur | 2015-07-06T17:11:21.450 | <p>I'm currently designing a system for my GCSE coursework. For the coursework, I am making a bollard system, controlled by the internet / traffic lights.</p>
<p>I've been experimenting with an Arduino Uno and Ethernet shield, in order to fulfill the control by the internet.</p>
<p>When I telnet into my Arduino, and send it the command "S#UP", the red LED comes on, and stays on for 30 seconds. If I send the command again, the Arduino does not turn on the LED, unless the command was send twice, consecutively. Also, if I were to send a different command, for example "S#DOWN", the LED does not even turn on, no matter how many times I send it.</p>
<p>Does anyone have any ideas for my? Anything I've blatantly missed or got myself confused on?</p>
<pre><code>#include <SPI.h>
#include <Ethernet.h>
String authcode, newstatus, command;
bool UP, DOWN, EMERGANCY;
long UPTime, DOWNTime, EMERGANCYTime, LastFlash;
bool NextFlash;
byte mac[] = {0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED};
IPAddress ip(192, 168, 1, 177);
IPAddress gateway(192, 168, 1, 1);
IPAddress subnet(255, 255, 255, 0);
EthernetServer server(1265);
char serverHost[] = "LambdaLaptop";
EthernetClient phpClient;
int R = 8;
int G = 9;
void setup() {
Ethernet.begin(mac, ip, gateway, subnet);
server.begin();
Serial.begin(9600);
Serial.println("=----------------------=");
Serial.println("=- Traffic Management -=");
Serial.println("=- System Loaded -=");
Serial.println("=----------------------=");
Serial.println("");
authcode = String("4b4fec50eaa13b98934c36863293b5cf");
LastFlash = millis();
NextFlash = HIGH;
pinMode(R, OUTPUT);
pinMode(G, OUTPUT);
}
void loop() {
EthernetClient client = server.available();
if (client) {
if (client.available() > 0) {
char thisChar = client.read();
command += thisChar;
ProcessCMD( command );
}else{
if(command.length() > 0 ){
command = String("");
}
}
}
if( UP ){
if( UPTime > millis() ){
digitalWrite(G, HIGH);
}else{
UP = false;
digitalWrite(G, LOW);
}
}else if( DOWN ){
if( DOWNTime > millis() ){
digitalWrite(R, HIGH);
}else{
DOWN = false;
digitalWrite(R, LOW);
}
}else if( EMERGANCY ){
if( EMERGANCYTime > millis() ){
if( LastFlash + 100 < millis() ){
digitalWrite(R, NextFlash);
if(NextFlash == LOW){
NextFlash = HIGH;
}else{
NextFlash = LOW;
}
}
}else{
EMERGANCY = false;
NextFlash = HIGH;
digitalWrite(R, LOW);
}
}
}
void ProcessCMD( String CMD ){
if(CMD == "S#UP"){
UP = true;
UPTime = millis() + 30000;
if(CMD.length() > 11){
command = String("");
}
}else if(CMD == "S#DOWN"){
// Make the thing go DOWN.
// GREEN LIGHT
DOWN = true;
DOWNTime = millis() + 30000;
if(CMD.length() > 11){
command = String("");
}
}else if(CMD == "S#EMERGANCY"){
// Make the thing go DOWN.
// Flash RED beacon.
EMERGANCY = true;
EMERGANCYTime = millis() + 15000;
if(CMD.length() > 11){
command = String("");
}
}else if(CMD == "TEST"){
UP = true;
}else if(CMD == "TEST2"){
UPTime = millis() + 30000;
}else{
if(CMD.length() > 11){
command = String("");
}
}
}
void SetStatus( String newstatus ){
if (phpClient.connect(IPAddress(192,168,1,10), 80)) {
phpClient.println(String("GET /setstatus.php?authcode=") + authcode + String("&status=") + newstatus + String(" HTTP/1.1"));
phpClient.println("Host: LambdaLaptop");
phpClient.println("User-Agent: arduino-ethernet");
phpClient.println("Connection: close");
phpClient.println();
phpClient.stop();
}
else {
Serial.println("Couldn't connect to the system!");
phpClient.stop();
}
}
</code></pre>
| <p>It would be far better to use char arrays instead of the String class (perhaps 11 bytes, if that is the largest command?).</p>
<p>eg.</p>
<p>const int MAX_COMMAND = 11;</p>
<p>char command [MAX_COMMAND];</p>
<hr />
<pre><code> if (client.available() > 0) {
char thisChar = client.read();
command += thisChar;
ProcessCMD( command );
</code></pre>
<p>You appear to be processing the command for every received byte. This means you will process "S", "S#", "S#D", "S#DO" etc. You need to wait until the whole command has arrived.</p>
<p>Then, once the command has been processed, empty out the command ready for next time.</p>
<hr />
<pre><code>void ProcessCMD( String CMD ){
</code></pre>
<p>Also all upper-case is usually reserved for constants, not variables like CMD.</p>
<hr />
<p>Finally, your detection of end-time by addition will fail when millis() wraps. This might not matter in a small test, but you may as well teach the right way. Instead of adding an interval, remember the start time and detect when the interval is up, eg. instead of:</p>
<pre><code>if( UPTime > millis() ){
</code></pre>
<p>You would write:</p>
<pre><code>if (millis () - UPTime >= 30000) {
</code></pre>
<p>Where UPTime is now the <em>start</em> of the interval (that is, you remember when the interval starts, and do the above subtraction to find the end of it).</p>
<hr />
<h2>References</h2>
<ul>
<li><p><a href="http://www.gammon.com.au/serial" rel="nofollow noreferrer">Processing incoming serial data</a> - the same techniques apply to Ethernet</p>
</li>
<li><p><a href="http://www.gammon.com.au/millis" rel="nofollow noreferrer">millis() overflow ... a bad thing?</a> - how to handle millis() wrap-around</p>
</li>
<li><p><a href="http://www.gammon.com.au/statemachine" rel="nofollow noreferrer">State machines</a> - managing events happening on the fly</p>
</li>
</ul>
|
13214 | |library|nrf24l01+|wireless| | Arduino can't see any library I have installed for nrf905? | 2015-07-07T06:24:09.590 | <p>nrf905\
nRF905-All-In-One-Shield\
RadioHead-master\
RadioHead\</p>
<p>None any of them are compiled with their examples without getting errors.</p>
<p><em>Error message:</em></p>
<pre><code>nRF905_RX.ino:4:20: fatal error: NRF905.h: No such file or directory
compilation terminated.
Error compiling.
</code></pre>
<p>Libraries used:</p>
<p><a href="http://www.github.com/elechouse/nRF905" rel="nofollow">Elechouse</a>
<a href="http://www.github.com/PaulStoffregen/RadioHead" rel="nofollow">RadioHead Github</a>
<a href="http://www.airspayce.com/mikem/arduino/RadioHead" rel="nofollow">RadioHead Doxygen</a>
<a href="http://www.github.com/zkemble/nRF905" rel="nofollow">zkemble/nRF905</a></p>
| <p>The errors you were getting when you compiled was because if the libraries were extracted straight to the Arduino library folder from the .zip, the file path becomes too long for the compiler to find it.</p>
<p>So what you need to do is to create a new folder in the libraries folder for each library. </p>
<p><strong>Note</strong>: you cannot do the standard <code>libraryName\src\foo.cpp</code> as this seems to give errors for these libraries (in that it does not find them). </p>
<p>What you need to do is to make a file in the <code>libraries</code> directory; for the <em>zkemble</em> one you can create a main folder called <code>nRF905</code>, then take the files under <code>nRF905/arduino/nRF905</code> from github and place them in the folder created earlier. It should look like this:
<img src="https://i.stack.imgur.com/ZTvGC.png" alt="enter image description here"></p>
<p>You should repeat this for the Elechouse one as well as it solved the problem too. i.e.</p>
<ul>
<li><code>C:\\...\libraries\NRF\examples\</code> </li>
<li><code>C:\\...\libraries\NRF\NRF905.cpp</code> </li>
<li><code>C:\\...\libraries\NRF\NRF905.h</code> </li>
<li><code>C:\\...\libraries\NRF\keywords.txt</code></li>
</ul>
<p>Also of importance is that once you have the library from Elechouse compiling you need to open up the .cpp file and go to line 16, where there is</p>
<pre><code>PROGMEM unsigned int freq_tab[10] = {
</code></pre>
<p>and to this add <code>const</code>, like so:</p>
<pre><code>PROGMEM const unsigned int freq_tab[10] = {
</code></pre>
|
13221 | |electronics| | What is the use of decoupling capacitor? | 2015-07-07T09:31:36.970 | <p>I dont understand what does the word "decoupling" mean? Where and Why it is used? Can anyone give me a brief idea>?</p>
| <p>Every time a logic circuit switches from a 0 to a 1 or a 1 to a 0, the 1 and 0 transistors are on at the same time for a short period of time. In MOS circuits, this is combined with the need to charge the gate of the 1 or 0 transistor (Charge is what capacitors store, gates of MOS transistors are capacitors!).</p>
<p>Since all wiring is inductive, the faster the current, the higher the impedance from the main power supply and the switching device (Your processor or sensor etc). The terms bypass and decoupling mean the same thing: You are providing a local charge well to supply fast current demands by bypassing the main power system, i.e. supplying current via a different path and thus decoupling the switching device from the inductively isolated main supply.</p>
<p>This is also why we used to use two types of capacitors for decoupling: A 0.1uF ceramic and a 1uF electrolytic for instance... You couldn't get the whole 1uF in a low resistance ceramic to cover both the Low and High speed transients without paying a lot so you used two or more parts, each covering a portion of the spectrum. Nowadays a single SMT ceramic with low ESR, low ESL and no lead wires can do the whole job and is usually pretty economical.</p>
<p>Another factor is radiation: A ringing voltage transient current through inductive wiring acts just like an antenna.</p>
|
13225 | |arduino-uno|arduino-ide|atmel-studio| | What changes I have to take care while coding from Atmel Studio instead of Arduino IDE? | 2015-07-07T10:05:30.937 | <p>-Are there any changes in Bootloader?
-Why is the coding different for same chip in different softwares?
-How to upload the program from Atmel Studio?</p>
| <p>Atmel cpp projects do not currently provide an option to upload using Arduino bootloader. Atmel only provides upload using hardware programmers.</p>
<p>The bootloader is deleted when you upload using a hardware programmer either from Atmel Studio or from the Arduino ide.</p>
<p>The underlying Atmel toolchain is not very different from the latest Arduino toolchain however Atmel does not know about the Arduino hardware/cores. You have to copy the Arduino core sources to your Atmel project if you want to compile for Arduino compatibility but that still does not give you bootloader upload.</p>
<p>It is not clear from your question if you have the Arduino sources in your cpp project already. If you do have the sources in your project then you can use avrisp mkII or other programmer to upload but the Arduino libraries might be an issue for you if you are using them.</p>
<p>There is another option in Atmel Studio however it might not be what you require ...</p>
<p>You can install the Visual <a href="https://gallery.atmel.com/Products/Details/c7a74708-c128-42fb-b670-29f501e85937?" rel="nofollow noreferrer">Micro plugin for Arduino</a> from the Atmel Gallery and work with standard Arduino sketch projects inside Atmel Studio. </p>
<p>The Visual Micro plugin provides full Arduino compatible sketch build and bootloader upload in Atmel Studio. Because of the nature of Arduino, the Visual Micro plugin automatically manages the include paths and Atmel project properties so that intellisense works in projects that contain .ino source code files. If the project does not contain .ino files then Visual Micro sleeps (does not interfere with cpp projects)</p>
<p>The plugin also provides other features such as a serial usb debugger, library manager, board manager, Arduino examples etc.</p>
<p>More about Visual Micro is <a href="http://www.visualmicro.com/" rel="nofollow noreferrer">here</a> </p>
<p>Tutorials are <a href="http://www.visualmicro.com/page/User-Guide.aspx" rel="nofollow noreferrer">here</a></p>
<p>Debugger overview is <a href="http://www.visualmicro.com/page/Debugging-for-Arduino.aspx" rel="nofollow noreferrer">here</a></p>
<p><img src="https://i.stack.imgur.com/PKBjO.png" alt="enter image description here"></p>
<p>Update:</p>
<p>There is no difference in program execution between uploading using a physical hardware programmer or using a usb cable via bootloader. </p>
<p>The Arduino libraries sources can be more complicated to include/compile in a project because they often include additional folders with private source code. This is more of an issue with older Arduino libraries that have a sub folder called \utility.</p>
|
13233 | |bluetooth|nrf24l01+|button|rf|wireless| | Choosing wireless tech for lowest possible lag | 2015-07-07T15:31:52.850 | <p>I am drafting a pub quiz project, where the Referee gives a signal and multiple players push their buttons. The first to push wins the right to give an answer.</p>
<p>I want all buttons (referee's + X players) to be wireless. Since the best quiz players can click a button within 10ms of the signal, it is very important that there is a very, very little variance in ping between different buttons. I cannot have players shouting "my button is laggy!" On the other hand, I don't want to use more expensive/complex tech than needed.</p>
<p>SO, what would be the optimal wireless tech to use? Please share your experience from similar projects (or just theoretical knowledge :) Here's what I researched so far (correct me if I'm wrong):</p>
<ol>
<li><p>Bluetooth 4 LE (as in RFduino)
Pros: 3-6ms latency (advertised), low energy
Cons: cost, not more than 7 buttons to the device</p></li>
<li><p>Wi-fi
Pros: 2ms latency (I justed pinged my wi-fi router), dozens of buttons if need be
Cons: cost, power-hungry</p></li>
<li><p>RF data tranceiver
Pros: dunno, cost seems to be a bit smaller
Cons: multiple buttons at the same frequency will probably create a lot of noise</p></li>
<li><p>Simplest "Radio remote"
Pros: zero lag since it's all electromechanical, no data
Cons: multiple buttons at the same frequency won't work</p></li>
</ol>
<p>So, did I miss anything? I appreciate any guidance.</p>
| <p>Low low tech solution.</p>
<ol>
<li><p>The transmitter sends out its clock signal on command.</p></li>
<li><p>The receiver just needs to detect detect the prrsence of that signal. </p></li>
</ol>
<p>The whole thing can be rf, or light based - for example one of the led lights can be configured as the transmitter.</p>
<p>Everything should be well within 1ms.</p>
|
13245 | |arduino-uno|shields|wifi| | Need help shrinking a code | 2015-07-07T23:12:59.407 | <p>I'am new to Arduino and c++</p>
<p>i get his code from the INTERNET</p>
<pre><code>void setup() {
Serial.begin(57600);
pinMode(13, OUTPUT);
}
int f = 0, pos;
void loop() {
boolean has_request = false;
String in = "";
if (Serial.available()) {
in = "";
while (true) { // should add time out here
while (Serial.available() == false) {}
in += (char)(Serial.read());
if (in.endsWith("\r\n\r\n")) {
has_request = true; break;
}
}
}
if (has_request) {
int i1 = in.indexOf("GET /blink?f="), i2;
if (i1 != -1) {
i2 = in.indexOf(" ", i1+13);
f = in.substring(i1+13, i2).toInt();
}
Serial.println("HTTP/1.1 200 OK\nContent-Type: text/html\nConnection: close");
String sr = "<!DOCTYPE HTML>\n";
sr += "<html>\n";
sr += "LED frequency: ";
sr += f;
sr += "Hz.</html>";
Serial.print("Content-Length: ");
Serial.print(sr.length());
Serial.print("\r\n\r\n");
Serial.print(sr);
has_request = false;
}
if (f>0) {
static unsigned long t = millis();
if (millis() > t + 1000/f) {
digitalWrite(13, 1-digitalRead(13));
t = millis();
}
}
}
</code></pre>
<p><a href="http://pastebin.com/mNQQamUg" rel="nofollow">see this link if you cant see the code formated here in the site</a></p>
<p>this code is used for the Arduino uno wifi shield
it is working perfectly except it is too complicated for me
while loop inside a while loop </p>
<p>and i don't want to do frequency i only need to send turn on or off
without any complexity </p>
<p>anyone could help me ? </p>
| <p>Here is my take at this. I realize that I did not really make the
program simpler, but hopefully better in some respects, as it avoids
blocking reads and heap memory allocation. Be warned however that I did
not test it. It compiles fine though.</p>
<p>Preamble, hopefully simple enough that it requires no comments:</p>
<pre class="lang-c++ prettyprint-override"><code>const uint8_t led_pin = 13;
void setup() {
Serial.begin(57600);
pinMode(led_pin, OUTPUT);
}
</code></pre>
<p>Next, here is a function to read the HTTP request. A few things are
worth noting in this function:</p>
<ul>
<li>It is non-blocking: if there is not data in the serial buffer, it will
return <code>NULL</code> immediately. This is to prevent the whole program from
hanging if the client does not terminate its request.</li>
<li>It only saves the first 31 bytes of the request. This is because
browsers tend to add lots of useless headers, which can be unfriendly
to the memory of a small Arduino. And the only interesting piece of
data is at the very beginning anyway.</li>
<li>The request terminating sequence (CR LF CR LF) is detected without
having to store it in the buffer, just by counting how many
consecutive bytes of that sequence we have already received.</li>
<li>Declaring the function as <code>static</code> makes it possible for the compiler
to inline it, which it does as it is only called from one place. This
makes for a smaller executable.</li>
</ul>
<pre class="lang-c++ prettyprint-override"><code>/*
* Non-blocking read. Returns the first bytes of the request in a static
* buffer, or NULL if we do not have a complete request yet.
*/
static char * read_request() {
static char buffer[32];
static uint8_t pos;
static uint8_t crlf_bytes; // bytes of "\r\n\r\n" received
while (Serial.available()) {
char c = Serial.read();
// Store the received byte if there is enough room.
if (pos < sizeof buffer - 1)
buffer[pos++] = c;
// Update the count of consecutive CRLF bytes received.
if ((c == '\r' && crlf_bytes % 2 == 0)
|| (c == '\n' && crlf_bytes % 2 == 1))
crlf_bytes++;
else
crlf_bytes = 0;
// Return the buffer if we have a complete request.
if (crlf_bytes == 4) {
buffer[pos] = '\0'; // terminate the string
pos = 0;
crlf_bytes = 0;
return buffer;
}
}
return NULL;
}
</code></pre>
<p>Parsing the request is done by a different function. Here, I do not
search for the "GET /blink?f=" string, because it <em>must</em> be at the very
beginning for the request to be valid.</p>
<pre class="lang-c++ prettyprint-override"><code>/*
* Returns the requested frequency, or 0 if nothing valid is found.
*/
static int parse_request(char *request) {
/* The "GET" should be at the very beginning. */
if (strncmp(request, "GET /blink?f=", 13) != 0)
return 0;
return atoi(request + 13);
}
</code></pre>
<p>Now we can send the response to the client, telling it how we parsed the
frequency. I avoid using <code>String</code>, as it involves heap allocation, and I
put the bulk of the response in PROGMEM (<code>F()</code> macro) to save RAM. I
also added a <code><title></code> to make it valid HTML.</p>
<pre class="lang-c++ prettyprint-override"><code>/*
* Tell the client how we understood the requested frequency.
*/
static void send_response(int freq) {
char freq_str[12];
itoa(freq, freq_str, 10);
Serial.print(F("HTTP/1.1 200 OK\r\n"
"Content-Type: text/html\r\n"
"Content-Length: "));
Serial.print(84 + strlen(freq_str));
Serial.print(F("\r\nConnection: close\r\n\r\n"
"<!DOCTYPE html>\n"
"<html><head><title>Blink</title></head>\n"
"LED frequency: "));
Serial.print(freq_str);
Serial.print(F(" Hz.\n</html>\n"));
}
</code></pre>
<p>The next function blinks the LED in a rollover-safe fashion. Storing the
current LED state in a static variable avoids a call to <code>digitalRead()</code>.</p>
<pre class="lang-c++ prettyprint-override"><code>static void blink_led(unsigned long toggle_time) {
static uint8_t led_state;
static unsigned long last_toggle;
unsigned long now = millis();
if (now - last_toggle > toggle_time) {
led_state = !led_state;
digitalWrite(led_pin, led_state);
last_toggle = now;
}
}
</code></pre>
<p>Putting it all together, the main <code>loop()</code> ends up being quite straight
forward:</p>
<pre class="lang-c++ prettyprint-override"><code>void loop() {
static unsigned long period = 1000;
char * request = read_request();
if (request) {
int freq = parse_request(request);
if (freq > 0) period = 1000 / freq;
send_response(freq);
}
blink_led(period);
}
</code></pre>
<p><strong>PS</strong>: My version is significantly larger than the original at the
source level (66 v.s. 44 source lines of code), but the compiled program
is smaller in both flash and RAM usage:</p>
<pre class="lang-c++ prettyprint-override"><code>text data bss version
5646 168 197 original
3316 40 218 my version
</code></pre>
|
13251 | |arduino-mega| | Arduino Mega vs. RasPi Pro Cons in 3D Printing | 2015-07-08T00:29:51.633 | <p>Recently I tooked a look at cheaper China 3D Printers and noticed they're all based on RepRap (mostly using Ramps for the electronics part) and the next day i saw a 2d Plotter based in the pi. Then I asked myself why the Pi isnt used in 3d printers.</p>
<p>Question:
Why is the Arduino Mega/Due more used in 3D Printing than the RasPi? What are the Pro's and Con's for 3D Printing on the two systems?</p>
| <p>A mutli-tasking operating system such as the Linux normally run on the pi is not particularly suited to doing hard real-time control such as coordinated pulse generation for multiple stepper motor axis trying to move as quickly as the rigidity and motor power will permit.</p>
<p>It is possible to use realtime extensions to the Linux kernel to get reasonable performance. And it is also possible to run something simpler than Linux on the pi. </p>
<p>However, it is also possible to use a far cheaper processor to get the actual G-code execution done (you don't really pay the Arduino cost premium when buying an ATmega on a dedicated board, so it's only a dollar or three more expensive than it "should be"). If one were to design printer electronics from scratch today, there are probably better choices, such as as ARM Cortex M0, M3 or M4 - but most of the printer designs came out of the same community where Arduino was a familiar choice, and there are probably more people willing to try to make small personal customizations to an Arduino codebase than there are willing to install the toolchain for a perhaps technically better, but less familiar solution. .</p>
<p>People do use Raspberry Pi's with 3d printers quite frequently though - they just use them for a different job: that of slicing and motion planning and potentially functioning as a network print server, which then drip-feeds the G code to the simpler (ATmega or whatever) based realtime executive. In effect, they use a pi as a cheap PC to host the ATmega-based printer, rather than dedicating an old PC to that job. </p>
<p>Ultimately, the rarely taken alternative of using a realtime Linux kernel extensions to control motion directly from a pi, vs the more common one of using an ATmega as a realtime motion delegate for the pi, are conceptually similar - it's just that in one case the realtime executive engine is a highest priority task on the main processor, and in the other it runs on a dedicated motion co-processor.</p>
|
13255 | |arduino-leonardo|tinygps| | Do I need a bubble sort or something easier? | 2015-07-08T04:10:17.760 | <p>I'm using an Arduino Leonardo and a GPSTiny++ library to parse NMEA strings from my GPS receiver. In this chunk of code I'm averaging all satellite SNR numbers for satellites which are locked (Being used for navigation). The avg value provides some general information on overall performance but I'm also really looking for the avg Top 4 values. </p>
<p>I believe I would need to do some sort of sorting algorithm. Increment through the top 4 and average those values. </p>
<p>Here's a snippet of my output window:
12/13 0.92 SNR=17 10 27 27 30 29 25 27 33 0 0 0 31 25.60 0.00</p>
<p>The second to last number is the average. </p>
<p>How do I get started? </p>
<pre><code>int totalSNR = 0;
float avgSNR = 0;
int count = 0;
Serial.print(F(" SNR="));
for (int i = 0; i < MAX_SATELLITES; ++i)
if (sats[i].active)
{
if (sats[i].snr > 0) {
count++;
totalSNR = totalSNR + sats[i].snr;
}
Serial.print(sats[i].snr);
Serial.print(F(" "));
}
avgSNR = float(totalSNR) / float(count);
Serial.print(avgSNR);
</code></pre>
| <p>Since you only need to know the 4 largest values in the array you don't need to sort the array, you just need to iterate through it and find the four largest values. This can be done in <code>O(n*k)</code> which is faster than any sorting algorithm you could use. However there is an issue of space since you would use an array to hold the previous largest numbers. Fortunately we can get around this by swapping the current largest value to the end of the array and ignoring it. So you can find the <code>k</code> largest values in an size <code>n</code> array in <code>O(n*k)</code> time complexity with <code>O(1)</code> space complexity. For fixed values if <code>n</code> and <code>k</code> the time complexity is <code>O(1)</code>.</p>
<pre><code> #include <stdio.h>
void swap (int& a, int& b);
int main () {
int sum = 0;
int max = -1; // I'm assuming your array will have non-negative numbers
int maxIndex;
int nums = 4; // we want the top "num" values in the array
const int arrSize = 9;
int arr[arrSize] = {36, 33, 19, 42, 47, 26, 50, 37, 38}; // random numbers
for (int i = 0; i < num; ++i){
// arrSize - i lets us ignore the previous max values
for (int j = 0; j < arrSize - i; j++){
if(arr[j] > max){
max = arr[j]; // store current max
maxIndex = j; // store the current max's index
}
}
sum += max; // running total
max = -1; // reset max
swap(arr[maxIndex], arr[arrSize-1-i]); // move current max to the end
}
float top4Avg = sum / 4.0;
printf("\nTop 4 average: %f\n", top4Avg);
}
// swaps a and b without a temp variable
void swap (int& a, int& b){
a = a ^ b; // ^ is the bitwise xor
b = a ^ b;
a = a ^ b;
}
</code></pre>
<p>First iteration: <code>{36, 33, 19, 42, 47, 26, 38, 37, 50}</code></p>
<p>Second iteration: <code>{36, 33, 19, 42, 37, 26, 38, 47, 50}</code></p>
<p>Third iteration: <code>{36, 33, 19, 38, 37, 26, 42, 47, 50}</code></p>
<p>Fourth iteration: <code>{36, 33, 19, 26, 37, 38, 42, 47, 50}</code></p>
<p>Also this was a really fun question I'd upvote but my rep isn't high enough.</p>
|
13263 | |arduino-uno|motor|electronics| | How come people connect their arduinos to buzzers without any coil protection? | 2015-07-08T09:11:38.080 | <p>If you connect your arduino to a motor you use this schematic:</p>
<p><img src="https://i.stack.imgur.com/ibbFi.png" alt="enter image description here"></p>
<p>However, when it comes to buzzers, which also have a coil, no one protects the circuit:</p>
<p><img src="https://i.stack.imgur.com/JMqnY.png" alt="enter image description here"></p>
<p>What the hell is going on? Are these just buzzers "coiless"? How can I find the type of buzzer I have?</p>
| <p>That kind of "buzzer" doesn't have a coil. It is a "Piezo Transducer" and uses a crystal to produce the sound.</p>
<p>When you're using a real speaker and producing sound you are doing it very differently to switching a motor or a relay on and off. You're generating a much smoother waveform and you don't have the sharp "ON-OFF" that causes a collapse of the magnetic field. You're actually gradually reducing the power and then reversing it to remove the magnetic field then apply a new one in the opposite direction (if you have wired it right of course).</p>
<p>Also the currents involved in driving a speaker like that are minuscule compared to switching a relay, especially when driven direct from the Arduino. For louder volumes you will use an amplifier, and that deals with the whole protection within itself since it is designed to drive a speaker.</p>
|
13268 | |string| | How to writte simple string compare? | 2015-07-08T11:47:07.673 | <p>I new to Arduino and I'm attempting to writte a simple string compare code like this:</p>
<pre><code>void loop()
{
distance(cm);
delay(200);
}
void distance(char[3] unit)
{
if (unit[] == "cm")
Serial.println("cm");
}
</code></pre>
<p>Could somebody please advise me how to writte it correctly?
Thanks in advance!</p>
| <pre><code>if (strcmp (unit,"cm") == 0) {
// matches cm
}
</code></pre>
<p>For syntax like this the intellisense in products such as Atmel Studio or Visual Studio can really help. Whilst you still need to understand what you might be looking for the intellisense makes all the available Arduino functions visible from the code. If you install the Arduino plugin then there will be an Arduino reference explorer in both ide's which explains everything. </p>
|
13275 | |keyboard| | Using Arduino To Control Boot Sequence of PC | 2015-07-08T15:14:07.387 | <p>I want to know if it is possible to use an arduino to tell a pc which os to boot to. I know It is possible to turn on the pc by wiring it to the motherboard pins with the power switch, and I know the arduino I have (<a href="http://rads.stackoverflow.com/amzn/click/B00E5WJSHK" rel="nofollow">http://www.amazon.com/SainSmart-ATmega328P-Development-Compatible-Arduino/dp/B00E5WJSHK/ref=sr_1_1?ie=UTF8&qid=1436368217&sr=8-1&keywords=sainsmart+uno+r3</a>) can act as a mouse or keyboard. Can that be done before the pc has booted however?</p>
| <p>So it might depend on how you implement it. With an Arduino Uno, your options for creating an HID device are limited to either reprogramming the 16u2 (which will require an ISP) or using a software USB implementation (like V-USB). If you go with the first method I'm pretty sure that will work as it will be a native USB connection. As for the second method, I'm not sure how well V-USB responds to having the USB host turning on while it is running. The best thing to do is just try it and see how well it works.</p>
<p>The bigger challenge you will run into is being able to select your PC operating system. Because this will be a one way connection, there is no way of knowing what state the computer is in and whether or not it is time to press a key yet or not. This means you will have to be timing things fairly accurately, which can be tricky unless you are careful. The internal oscillator is not very accurate (but probably still accurate enough) and interrupts used for communicating with USB can block the main loop. That is not to mention any variations the computer might have in its boot process.</p>
<p>A good alternative method would be to set up a bootloader on your PC that can be controlled via a serial port. GRUB2 is a popular one that does support a <a href="https://wiki.archlinux.org/index.php/Working_with_the_serial_console" rel="nofollow">serial console</a>. All you would need to do is add a level adjuster to adapt the Arduino UART to RS232, then set up the code to wait for the GRUB prompt and then send the command necessary to select which OS you wish to use.</p>
|
13285 | |arduino-uno|programming|timers|display| | Arduino UNO with CD4510 Counter | 2015-07-09T03:12:15.517 | <p>I am new in Arduino but I have experience in electronics.</p>
<p>I was wondering how can I make a countdown timer using a CD4510 and an Arduino UNO. I know you would suggest that I should connect my seven segment display on the IO pins but I can't do that because I will use multiple seven segment displays.</p>
| <p>I can use CD4510 to make a countdown timer, I just need to connect CLOCK INPUT to the Digital IO pins located in the arduino microcontroller and use pulse with modulation (pwm) for the code</p>
|
13287 | |arduino-uno|programming|interrupt|sketch| | Interrupt fires multiple times | 2015-07-09T04:32:24.343 | <p>I have a Photo Interrupter which I am using to count the RPM of a motor.</p>
<p>I am incrementing an integer to show the amount of interrupts there have been.</p>
<p>The issue is that there can be several interrupts fired for each time the "beam" of the Photo Interrupter is broken.</p>
<p>I have a 5mm length of plastic which breaks the "beam". If I make the plastic shorter than that, the Photo Interrupter doesn't pick up the break.</p>
<p>I am using the following, very basic code: </p>
<pre><code>int pin = 13;
volatile int tcnt = 0;
volatile int state = LOW;
void setup() {
Serial.begin(9600);
pinMode(pin, OUTPUT);
attachInterrupt(0, blink, CHANGE);
}
void loop() {
Serial.println(tcnt);
digitalWrite(pin, state);
}
void blink() {
tcnt = tcnt + 1;
state = !state;
}
</code></pre>
| <p>If you want to count RPM, maybe this link will help you:
<a href="http://rjbotics.blogspot.in/2015/07/counting-real-time-rpm-with-ir-sensors.html" rel="nofollow">http://rjbotics.blogspot.in/2015/07/counting-real-time-rpm-with-ir-sensors.html</a></p>
|
13291 | |nrf24l01+|mpu6050| | Using nrf24l01 with mpu 6050 unstable | 2015-07-09T05:29:12.983 | <p>I am trying to connect the wireless module nrf24l01 with the gyro mpu-6050. Each works perfectly on its own. However, when connecting both to a single atmega328 (in order to send over wireless the gyro data), the code runs for between 30 seconds and 5 minutes. </p>
<p>I have seen many people have issues, none of the suggestions have worked, but it seems like it is more about the combination than the mpu itself. I have not had any errors, in that all the attempts have uploaded fine.</p>
<p>Some things I have tried (If you have experience with this device, im sure you will know what i am referring to ):
Changing clock rates from 24 to 12, and 400 to 200
Changing the header file for mpu from 100 hz to 20 hz and back
Adding pullup and pulldown resistors on sla/sda
Using external variable power supply to make sure exact voltage
Powering devices off arduino 3.3 and external 3.3
Running code without using serial reader on computer and just transmitting data</p>
<p>Edit:</p>
<p>After more debugging, I reduced the issue (I think). As each module works fine independently, i thought there could be a code issue. It seems though, that the issue is the combination of buffers. I don't think this is exactly right, but to us it seems like the gyro needs to run quickly to stop the risk of causing the arduino to hang(even though we clear the buffer). </p>
<p>The second part is the wireless. It seems like the code is looking by default for an acknowledgment the package is received. This slows down the broadcasting. So, if we disable the ack requirement, the gyro becomes stable. However, the receiver stops receiving any packets at all. If someone knows why, please explain. </p>
<p>So what we thought would work is by sending only some packets as the write with ack on a particular pipe. This way, the gyro will be able to run stably, and the data can sometimes be sent and we can see if this is really the problem. Again, this does not get recognized by the receiver at all.</p>
<p>Questions:
Does it make sense that the buffers are working against eachother, and this is not solvable through hardware.
Is there a clear reason why the receiver can not find packets that are being sent, just without the ack requirement?</p>
| <p>I could not figure out what was wrong, but I changed to this library for NRF24: <a href="http://tmrh20.github.io/RF24/" rel="nofollow">http://tmrh20.github.io/RF24/</a></p>
<p>and I started using the GY-85 with the FreeIMU Library : <a href="http://www.varesano.net/projects/hardware/FreeIMU" rel="nofollow">http://www.varesano.net/projects/hardware/FreeIMU</a></p>
<p>Following this advice:
<a href="http://forum.arduino.cc/index.php?topic=164222.msg1539961#msg1539961" rel="nofollow">http://forum.arduino.cc/index.php?topic=164222.msg1539961#msg1539961</a></p>
<p>It works now, so if it was SRAM as @Avamander suggested, it was not on my side.</p>
|
13292 | |arduino-uno|uploading|atmega328|icsp| | Have I bricked my Arduino Uno? Problems with uploading to board | 2015-07-09T05:46:30.023 | <p>I can't upload sketches to my Arduino Uno. </p>
<ul>
<li>Have I "bricked" it? </li>
<li>What steps can I take to work out what is wrong?</li>
<li>What can I do to fix it?</li>
</ul>
| <p>I have bricked 2x ATMega328P on my Arduino Uno board due to static (I think).</p>
<p>The static seems to have killed the TX pin and hence the program can't be downloaded using the USB cable.</p>
<p>The easiest solution is to replace the microcontroller. You can buy a new ATMega328P DIP programmed with the Arduino bootloader (<a href="https://www.adafruit.com/product/123" rel="nofollow noreferrer">such as this one from Adafruit</a>) and you are ready to go again.</p>
<p>Alternatively, you can still program the ATMega328P's by using the Atmel Ice or AVRISPmkII programmer or by using another Arduino as an ICSP programmer. When you do, all but the Tx pin work fine.</p>
|
13300 | |arduino-mega|shields|sd-card|audio| | Write to file in SD card in wave shield V3 | 2015-07-09T11:57:34.017 | <p>I just started tinkering with Arduino. I'm curious to know though, is it possible to read and write to a file stored in the SD card in the Wave shield v3 by Elechouse? I'm able to play files stored in said SD card, but I don't know how I'd go about writing some logs. I'm using an Arduino Mega.</p>
<p>Thanks in advance.</p>
| <p>No, you cannot. The shield is basically a cheap WAV or AD4 (whatever THAT is) playing chip which loads the audio data direct from an (old, small) SD card. The only control you have is IO pins that emulate pressing the buttons on an MP3 player.</p>
|
13304 | |sensors|power|arduino-nano|battery|solar| | Choose the correct solar panel and battery for solar use | 2015-07-09T17:19:43.970 | <p>I am planning to build a weather station powered by solar power. I want to use an Arduino Nano because it's low power requirement. I want to connect some basic sensors to it (temperature, humidity…) as well as an anemometer, a wind vane and a rain gauge. The weather data should be sent wireless via 433 mhz to a raspberry pi, which acts as a web server. I do not have power cable access to the Arduino so solar is the only option.</p>
<p>Which solar panel should I use? I was planning to use 2 2.5W 5.5V panels which charge a Lithium-Ion battery which powers the Arduino using a step up converter. Assuming I have 2-4h of direct sunlight per day and I want to query the sensors every 5 minutes, how big of a battery should i choose? I don't want it to go out of power and want it to last a couple of days without sun.</p>
| <p>I won't be able to tell you which solar panel or battery to use, but I can tell you how to figure that out.</p>
<h2>Battery</h2>
<p>For the battery there are a few different ways to figure this out:</p>
<ol>
<li>The most common way to do this at the professional level is to build the device and run it attached to an energy meter and measure it for an hour or two performing its usage, and use that to calculate how much it will use over a 48 hour period. That being said that type of test equipment is not really a hobbyist piece of equipment and probably not something you are wanting to obtain for this project.</li>
<li>You can try and use the datasheets for all of your components to determine their idle and active current draw is, add them up for idle and active, adjust the values based upon the efficiency of your step up converter (so if it only 75% efficient, divide them by .75), guesstimate how long your sensor read process will take, multiply your active current draw times the voltage and times the time it will take (in hours, so if this is a few seconds, it will be a really small decimal), multiply your idle current draw times the voltage and times .083 hours (5 minutes), add those two together multiply it times 12 (12 - 5 minute periods per hour) and then by 48 (two days) and that will be an estimate of your energy usage for two days. Now this will be a very rough estimate as the datasheets only provide nominal values, and their actual usage in practice may be different, which leads me to the final option...</li>
<li>A hybrid between the two above solutions. Set up your device and have it read the sensors and transmit continuously. Then use a multi-meter to measure the current usage of it actively being used. Repeat the measurement again but this time with it running on an indefinite timer to simulate being idle. Then take those two numbers and use the above formula substituting the datasheet estimates with your actual measurements to get a much more accurate picture of what your energy usage will be.</li>
</ol>
<p>Once you have your energy usage (this will be in milli-Watt-Hours or mWH) pick a battery voltage you will be using (this is based on the charge circuit you are using, typically, single cell lithium ion batteries are 3.7 or 4.2, with multi-cell batteries being multiples of those), divide your energy by the voltage to get the power (in milli-Amp-Hours or mAH) and you'll want to pick a battery greater than that. You'll also want to double check the data sheet of your step up converter and see what the drop out voltage is, and then compare that to the datasheet for the battery and see at what capacity it hits that voltage. You'll want to make sure that it is at least 80%. Otherwise you'll have to pick a different battery with a larger capacity, or a different step up converter with a lower dropout voltage.</p>
<h2>Solar Panel</h2>
<p>For the solar panel, what you will want to do is get a battery charger designed specifically for use with solar panels. This is because when it says 5.5v solar panel, that is it's nominal voltage in full sunlight, however, it most often will not be that and will vary greatly throughout the day. What this means is that solar panels are basically on unregulated power supply, and most battery chargers require a regulated power source. With a solar specific batter charger, it is designed such that it can handle voltage variation and sudden dropouts. Usually these chargers come with a recommendation as far as voltage and current requirements and those specifications should form the basis of your solar panel selection.</p>
<p>So for example, if you have a battery, on the datasheet it will list what its charge current is, and you'll want to make sure you have a charger circuit that can supply that amount of current. Then you'll want to take a look at the datasheet for the charger circuit, see what current it requires and then make sure that the solar panel can provide that current.</p>
|
13317 | |arduino-yun|string|adafruit| | iterate through values in an array of strings to print | 2015-07-09T20:55:59.813 | <p>I (think I) am trying to iterate through the values of an array and print the string to a tft. I have declared the array of 4 strings, and that works fine. But when I try to print it, I get garbage. Am I missing a nuance of print? Or do I just not understand how to use arrays and strings...?</p>
<p>The code is as follows:</p>
<p>Declarations:</p>
<pre><code>//Active System
char hvacSystems[4][5] = {"Off", "Fan", "Cool", "Heat"};
int activeSystem = 0;
String displayActiveSystem = hvacSystems[activeSystem]; <-- Should now be String "off"
</code></pre>
<p>Use (note the fake if statement for the question)</p>
<pre><code> if(systemNeedsToBeCycled){
activeSystem++;
displayActiveSystem = hvacSystems[activeSystem]; <-- Should now be String "Fan"
tft.print(displayActiveSystem);
}
</code></pre>
<p>Instead I get random characters most of the time, sometimes nothing.</p>
<p>In case its a memory thing, please know that:</p>
<p>Sketch uses 26,480 bytes (92%) of program storage space. Maximum is 28,672 bytes. Global variables use 1,126 bytes (43%) of dynamic memory, leaving 1,434 bytes for local variables. Maximum is 2,560 bytes.</p>
| <p>I think this is the correct way to create an array of C strings:</p>
<pre><code> char * hvacSystems[] = {"Off", "Fan", "Cool", "Heat"};
int activeSystem = 0;
char * displayActiveSystem = hvacSystems[activeSystem];
if(systemNeedsToBeCycled){
activeSystem++; // make sure to set a bound for this variable
displayActiveSystem = hvacSystems[activeSystem];
tft.print(displayActiveSystem);
}
</code></pre>
<p>Since strings are basically stored as char pointers so an array of strings is an array of char * variables. Or you could create an array of Arduino strings:</p>
<pre><code> String hvacSystems[] = {"Off", "Fan", "Cool", "Heat"};
int activeSystem = 0;
String displayActiveSystem = hvacSystems[activeSystem];
if(systemNeedsToBeCycled){
activeSystem++; // make sure to set a bound for this variable
displayActiveSystem = hvacSystems[activeSystem];
tft.print(displayActiveSystem);
}
</code></pre>
|
13328 | |arduino-mega|xbee|wireless| | xbee communication not established between arduino | 2015-07-10T02:07:05.103 | <p>I have 2 Xbee Series2 modules, one set to Coordinator AT (Connected to PC with XCTU via USB dongle) and other set to Router AT(Connected to Arduino is connected to PC USB... RX>TX TX>RX and 5V GND)</p>
<p><a href="http://continentalee.com.sg/xbee-adapter" rel="nofollow">http://continentalee.com.sg/xbee-adapter</a>
My xbee adapter</p>
<p>I have the programme uploaded into Arduino, a very simple sketch to test xbee wireless communication.</p>
<p>Code is here</p>
<pre><code>char msg = ' '; //contains the message from arduino sender
const int led = 13; //led at pin 13
void setup() {
Serial.begin(9600);//Remember that the baud must be the same on both arduinos
pinMode(led,OUTPUT);
}
void loop() {
while(Serial.available() > 0) {
msg=(char) Serial.read();
if(msg=='H') {
digitalWrite(led,HIGH);
}
if(msg=='L') {
digitalWrite(led,LOW);
}
delay(1000);
}
}
</code></pre>
<p>The problem comes.</p>
<p>When I type "H" in the Serial Com, the led light up, and the letter "H" appears in the XCTU console.</p>
<p>however, when I type something into the XCTU console, nothing appears on my Serial monitor and no light is seen on arduino</p>
<p>Thank you for your help in advance.</p>
| <p>Your example does not show your code that sends correctly but I will assume that it used 9600 speed and that the xbees are configured to 9600.</p>
<p>Not sure if this will help ...</p>
<blockquote>
<p>Arduino is connected to PC USB... RX>TX TX>RX </p>
</blockquote>
<p>1) In this case maybe you should ensure that xbee tx is connected to the correct rx pin on the Arduino? I know you have stated this above but with the basic xbee configuration, if data works one way then it should also work the opposite way.</p>
<blockquote>
<p>however, when I type something into the XCTU console, nothing appears on my Serial monitor and no light is seen on arduino</p>
</blockquote>
<p>2) Your example doesn't show any code to send data to XCTU and the pin13 LED will only light up when an 'H' is sent from XCTU</p>
<p>You could try this for better diagnostics</p>
<pre><code> void loop() {
while(Serial.available() > 0) {
msg=(char) Serial.read();
Serial.print("data arrived from xctu: ");
Serial.print(msg);
Serial.println();
if(msg=='H') {
digitalWrite(led,HIGH);
}
if(msg=='L') {
digitalWrite(led,LOW);
}
delay(1000);
}
}
</code></pre>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.