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
|
---|---|---|---|---|---|
9067 | |ethernet| | Using ethernet, how do I navigate to a page on my local server | 2015-03-06T16:36:27.983 | <p>I want to access the following page on my local using my Arduino with ethernet shield" 192.168.1.2/zombie/arduino.php. My arduino is conencted to a PC through a router. The system keeps timing out</p>
<p>I am using the following code:</p>
<pre><code>#include <Ethernet.h>
#include <SPI.h>
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
byte ip[] = { 192,168,1,3 };
char server[] = "192.168.1.2/zombie/arduino.php";
EthernetClient client;
void setup()
{
Ethernet.begin(mac, ip);
Serial.begin(9600);
delay(1000);
Serial.println("connecting...");
int res = client.connect(server, 80);
Serial.println(res);
if (res) {
Serial.println("connected");
client.println();
} else {
Serial.println("connection failed");
}
}
void loop()
{
if (client.available()) {
char c = client.read();
Serial.println("data:");
Serial.println(c);
}else{
Serial.println("NA");
}
if (!client.connected()) {
Serial.println();
Serial.println("disconnecting.");
client.stop();
for(;;)
;
}
}
</code></pre>
| <p>I discovered the answer after some testing.</p>
<p>The server var:</p>
<pre><code>char server[] = "192.168.1.2/zombie/arduino.php";
</code></pre>
<p>should only contain the ip address. So it should look like this:</p>
<pre><code>byte server[] = { 192,168,1,2 };
</code></pre>
<p>The additional URL elements should be added using:</p>
<pre><code>client.println("GET /zombie/arduino.php");
</code></pre>
<p>after a connection has been established</p>
<p>The final code should look like this:</p>
<pre><code>#include <Ethernet.h>
#include <SPI.h>
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
byte ip[] = { 192,168,1,3 };
byte server[] = { 192,168,1,2 };
EthernetClient client;
void setup()
{
Ethernet.begin(mac, ip);
Serial.begin(9600);
delay(1000);
Serial.println("connecting...");
int res = client.connect(server, 80);
Serial.println(res);
if (res) {
Serial.println("connected");
client.println("GET /zombie/arduino.php");
client.println();
} else {
Serial.println("connection failed");
}
}
void loop()
{
if (client.available()) {
char c = client.read();
Serial.println("data:");
Serial.println(c);
}else{
Serial.println("NA");
}
if (!client.connected()) {
Serial.println();
Serial.println("disconnecting.");
client.stop();
for(;;)
;
}
}
</code></pre>
|
9071 | |i2c|string| | How do I send a string to master using i2c | 2015-03-06T20:17:45.693 | <p>I want to write an Arduino program that simply recieves a string (via the I2C wire library) from a master Arduino, then waits for a request, and sends that string back.</p>
<p>Here is my code:</p>
<pre><code>#include <Wire.h>
void setup()
{
Wire.begin(4);
Wire.onReceive(receiveEvent);
Wire.onRequest(requestEvent);
}
String data = "";
void loop()
{
}
void receiveEvent(int howMany)
{
data = "";
while( Wire.available()){
data += (char)Wire.read();
}
}
void requestEvent()
{
Wire.write(data);
}
</code></pre>
<p>I read in the API that the write() function accepts a string, but I keep getting a "No matching function for call" error. I tried to simply replace</p>
<pre><code>Wire.write(data);
</code></pre>
<p>with </p>
<pre><code>Wire.write("test");
</code></pre>
<p>and that worked without error. Why is this the case? </p>
| <p><code>data</code> is a <a href="http://arduino.cc/en/Reference/StringObject"><code>String</code></a>. <code>"test"</code> is a <a href="http://arduino.cc/en/Reference/string"><code>char*</code></a>. <a href="http://arduino.cc/en/Reference/WireWrite"><code>Wire.write()</code></a> has no prototype that takes a <code>String</code>.</p>
<pre><code>Wire.write(data.c_str());
</code></pre>
|
9073 | |i2c| | How does the Arduino send more than 6 bytes via I2C | 2015-03-06T20:32:47.623 | <p>I have been working with the wire library (I2C) to send data from one Arduino to another. I read that the Arduino can only send 6 bytes per cycle, but I have been able to transfer much larger strings. This code works without error:</p>
<pre><code> Wire.beginTransmission(4); // transmit to device #4
for(int i = 0; i < 20; i ++){
char rand = random(65, 100);
Wire.write(rand);
}
Wire.endTransmission(); // stop transmitting
</code></pre>
<p>How is this possible? It seams that 32 characters can be sent without trouble.</p>
<p>I read this here: <a href="http://arduino.cc/en/Tutorial/MasterReader" rel="nofollow">http://arduino.cc/en/Tutorial/MasterReader</a></p>
<blockquote>
<p>Arduino 1, the Master, is programmed to request, and then read, 6 bytes of data sent from the uniquely addressed Slave Arduino.</p>
</blockquote>
<p>Now that I look at this again (after reading the responses) I think that the limit was set in the code sample.</p>
| <p>There is no reason to believe there is a 6 byte limit.</p>
<p>The <a href="http://arduino.cc/en/Reference/Wire" rel="nofollow">Arduino Reference</a> makes no mention of a 6 byte limit.</p>
<p>The <a href="https://github.com/arduino/Arduino/blob/master/hardware/arduino/avr/libraries/Wire/Wire.cpp" rel="nofollow">Wire.cpp</a> defines 'txBuffer[BUFFER_LENGTH];' where <a href="https://github.com/arduino/Arduino/blob/master/hardware/arduino/avr/libraries/Wire/Wire.h" rel="nofollow">BUFFER_LENGTH = 32 (defined in Wire.h)</a>. The maximum is 32 bytes, just as you noticed.</p>
|
9074 | |programming|pins|arduino-micro| | Detect external ground on an input pin | 2015-03-06T21:03:48.060 | <p>I am making a bike alarm for my bike. I haven't started yet.
Basically, I'm thinking of a pin to be connected to the metal post (to which the bike is locked.) I want to detect if that connection (to the ground via the metal post) is broken.
Is that possible?</p>
| <p>How about fastening a wire to the post, and then the other end, on the bike, goes into a "jack" (the sort of thing you plug headphones into). With the wire inserted, it makes a connection, and the Arduino knows the wire is there. As the thief steals the bicycle the plug (or loose wire) is pulled from the jack, breaking the connection. i.e.</p>
<p><a href="https://i.stack.imgur.com/2z3Oe.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/2z3Oe.png" alt="Bicycle protection"></a></p>
|
9082 | |sensors|ir|proximity| | How to increase the detection distance on Arduino KY-032 obstacle Avoidance sensor? | 2015-03-07T10:39:14.627 | <p>We've got an Arduino KY-032 obstacle avoidance sensor, and have spent a decent time searching and researching to find a detailed data sheet/manual to figure out how it works; but there aren't any detailed information on the module.</p>
<p><img src="https://i.stack.imgur.com/ZAHF0.png" alt="Arduino KY-032"></p>
<p>One of the few instructions <a href="https://tkkrlab.nl/wiki/Arduino_KY-032_Obstacle_avoidance_sensor_module" rel="nofollow noreferrer">here</a> says that the potentiometers on the chip are used to adjust the distance, but I've tried all different settings and the maximum I can get is 10 centimeters. I've tried different surfaces with different reflectivity levels, but it doesn't really differ much.</p>
<p>Any idea how to increase the distance on this? Anything to do with the enable jumper?</p>
<p><strong>Update:</strong> Here's the related code to the obstacle detection:</p>
<pre><code>void loop() {
// check the network connection once every 10 seconds:
val = digitalRead (buttonpin) ;// digital interface will be assigned a value of 3 to read val
if(full==1 && val==LOW) {
Serial.print("Bin Full");
delay(5000);
} else {
if (val == LOW) {
// When the obstacle avoidance sensor detects a signal, LED flashes
digitalWrite (Led, HIGH);
delay(2000);
if(digitalRead(buttonpin)==LOW) {
delay(2000);
if(digitalRead(buttonpin)==LOW) {
full = 1;
}
}
count++;
//printCurrentNet();
sendData();
} else {
digitalWrite (Led, LOW);
if(full==1) {
count = 0;
}
full = 0;
}
}
}
</code></pre>
| <p>The wizecode page has some nice info. However the R5 pot (near the EN jumper) does not change the duty cycle but directly the current to the IR LED - still affects the brightness though. Too much current seems to trigger false positives - depends on your additional optical shielding. I put some black heat shrink tubing over the sensor - with a hole punched in for the sensor to see though.
Also the R6 pot does not really "fine tune" the frequency, more like "coarse tune" - even a small nudge can detune by a kHz, greatly reducing the sensitivity.</p>
<p>If you use the EN jumper, a suddenly appearing object gives a short pulse, but then the disturbance signal suppression kicks in turns sensitivity down and 'unsees' the object. Also slowly appearing objects are not recognized for that reason. Only very near objects (a few cm) give a strong enough signal to overcome that sensitivity attenuation.</p>
<p>What I found somewhat irritating: Setting EN to LOW lets the IR LED steady on instead of off, which I would have expected. That might irritate the sensor more than necessary. Also draws more power (maybe even a lot, depending on R5 current setting).</p>
<p>Funny enough, you can get a somewhat analog behaviour from this sensor if you measure how long it takes from activating the EN pin to the sensor output getting low. The nearer the object is, the faster it reacts. Near objects take ~190us, farther objects more than 400us. Not nearly a linear behaviour though. Also depends on distance, size, angle, IR reflectivity and IR LED power.
However it can detect a person in more than 1m distance.</p>
|
9083 | |arduino-nano|avrdude|atmel-studio| | Atmel Studio and Arduino IDE compiles the same code different | 2015-03-07T11:10:52.217 | <p>Before going in details I need to say I am trying to program Arduino Nano board with atmega328p.
Here is my code in Atmel Studio;</p>
<pre><code>#include <avr/io.h>
#include <string.h>
#include <avr/interrupt.h>
int received;
int pinState = 0;
ISR(USART_RX_vect)
{
//cli();
while(!(UCSR0A&(1<<RXC0))){};
//clear the USART interrupt
received = UDR0;
UDR0 = received;
//sei();
}
int main(void)
{
//DDRB |= (1 << PORTB3);
//DDRD |= (1 << PORTD3);
DDRD = 0xFF;
DDRB= 0xFF;
#define F_CPU 16000000
TCCR2A = _BV(COM2A1) | _BV(COM2B1) | _BV(WGM21) | _BV(WGM20);
TCCR2B = _BV(CS22);
TCCR0A |= _BV(WGM00) | _BV(WGM01) | _BV(COM0A1);
TCCR0B |= _BV(CS02);
#define USART_BAUDRATE 9600
#define UBRR_VALUE (((F_CPU / (USART_BAUDRATE * 16UL))) - 1)
UBRR0H = (uint8_t)(UBRR_VALUE>>8);
UBRR0L = (uint8_t)UBRR_VALUE;
UCSR0B |= (1 << RXEN0) | (1 << TXEN0) | (1 << RXCIE0); // Turn on the transmission, reception, and Receive interrupt
UCSR0C |= (1<<UCSZ01)|(1<<UCSZ00);
//DDRB |= (1 << DDB1)|(1 << DDB2);
sei();
while(1)
{
}
return 0;
}
</code></pre>
<p>And here is the code in Arduino IDE;</p>
<pre><code>#include <avr/io.h>
#include <string.h>
#include <avr/interrupt.h>
int received;
int pinState = 0;
ISR(USART_RX_vect)
{
//cli();
while(!(UCSR0A&(1<<RXC0))){};
//clear the USART interrupt
received = UDR0;
UDR0 = received;
//sei();
}
void setup() {
DDRD = 0xFF;
DDRB= 0xFF;
#define F_CPU 16000000
TCCR2A = _BV(COM2A1) | _BV(COM2B1) | _BV(WGM21) | _BV(WGM20);
TCCR2B = _BV(CS22);
TCCR0A |= _BV(WGM00) | _BV(WGM01) | _BV(COM0A1);
TCCR0B |= _BV(CS02);
#define USART_BAUDRATE 9600
#define UBRR_VALUE (((F_CPU / (USART_BAUDRATE * 16UL))) - 1)
UBRR0H = (uint8_t)(UBRR_VALUE>>8);
UBRR0L = (uint8_t)UBRR_VALUE;
UCSR0B |= (1 << RXEN0) | (1 << TXEN0) | (1 << RXCIE0); // Turn on the transmission, reception, and Receive interrupt
UCSR0C |= (1<<UCSZ01)|(1<<UCSZ00);
//DDRB |= (1 << DDB1)|(1 << DDB2);
sei();
}
void loop() {
// wait for a second
}
</code></pre>
<p>As you can see these codes are exactly the same (except the setup-loop format)
Now I am using exact same parameters for AVRdude;</p>
<p><strong>-CF:\arduino-1.0.6\hardware/tools/avr/etc/avrdude.conf -v -v -v -v -patmega328p -carduino -P\.\COM9 -b57600 -D -Uflash:w:</strong> and following the hex file that is created after compile. But when I examine the verbose output of avrdude.exe they are different.</p>
<p>Arduino program works but the program uploaded using Atmel Studio does not. For more information everything about avrdude and parameters are working and it uploads and doesnt give any errors.</p>
<p>I chose atmega328p in Atmel Studio which is correct because I am using arduino nano board.</p>
| <p>I found the solution (or what the problem is). Avrdude not only requires MCU model but also programmer parameter. If you are using any of Arduino based boards you need to add <strong>-c programmer id</strong> do avrdude input parameters.</p>
|
9089 | |programming|motor| | Vibrating motors with different intervals | 2015-03-07T14:50:07.447 | <p>For my project, I have 3 ultrasonic sensors and 3 vibrating motors; the motors need to buzz for a small amount of time, then wait for a specific time that corresponds whith the range of the ultrasonic sensor, then muzz again.</p>
<p>The problem I'm having is that I used delays at first but that would cause the third motor only to buzz after the first two already waited.</p>
<p>I basically need something like "digitalWrite(motorPin_1, HIGH) for X amount of time;"
and at the same moment it has to start "digitalWrite(motorPin_2, HIGH) for X amount of time;". </p>
<p>Sadly I can't get the motors to vibrate any softer or harder, so I use these intervals.</p>
| <p>Like Edgar commented, you need to check out Blink Without Delay (<a href="http://arduino.cc/en/Tutorial/BlinkWithoutDelay" rel="nofollow">http://arduino.cc/en/Tutorial/BlinkWithoutDelay</a>). Learn what they are doing and you will get this just fine. </p>
<p>Also, I recommend you learn to use libraries. This library can do exactly what you are asking for: <a href="http://playground.arduino.cc/Main/LibraryList#Timing" rel="nofollow">http://playground.arduino.cc/Main/LibraryList#Timing</a> --> click on the "Timer" library by Simon Monk & J Christensen. Follow the examples there. This library works great!</p>
<p>Here is a complete set of code to answer your question. It should work perfectly for you. </p>
<pre><code>/*
buzz3Motors.ino
By Gabriel Staples
http://electricrcaircraftguy.blogspot.com/
7 March 2015
To help this person here: http://arduino.stackexchange.com/questions/9089/vibriting-motors-with-different-intervals
*/
#include "Timer.h"
Timer t;
boolean buzzMotor1Now = false, buzzMotor2Now = false, buzzMotor3Now = false;
unsigned int buzzTime = 1000; //ms
byte buzzPin1 = 11;
byte buzzPin2 = 12;
byte buzzPin3 = 13;
void setup()
{
//set pins to outputs
pinMode(buzzPin1, OUTPUT);
pinMode(buzzPin2, OUTPUT);
pinMode(buzzPin3, OUTPUT);
}
void loop()
{
//UPDATE YOUR BUZZMOTOR BOOLEANS HERE, and set to true if necessary
/**
* This method will generate a pulse of pulseValue, starting immediately and of
* length period. The pin will be left in the !pulseValue state
*/
//Function format: int8_t pulseImmediate(uint8_t pin, unsigned long period, uint8_t pulseValue);
//see here: https://github.com/JChristensen/Timer/blob/master/Timer.h
if (buzzMotor1Now==true)
{
buzzMotor1Now = false; //reset
t.pulseImmediate(buzzPin1,buzzTime,HIGH);
}
if (buzzMotor2Now==true)
{
buzzMotor2Now = false; //reset
t.pulseImmediate(buzzPin2,buzzTime,HIGH);
}
if (buzzMotor3Now==true)
{
buzzMotor3Now = false; //reset
t.pulseImmediate(buzzPin3,buzzTime,HIGH);
}
t.update(); //update all timer events
}
</code></pre>
<p>Note that only 10 timer events can be ongoing at any given time. If you want to have more you must increase the MAX_NUMBER_OF_EVENTS value in the Timer.h (<a href="https://github.com/JChristensen/Timer/blob/master/Timer.h" rel="nofollow">https://github.com/JChristensen/Timer/blob/master/Timer.h</a>) file.</p>
<p>PS. Also look into the "oscillate", "after", "every", and "pulse" functions, that the library also supports.</p>
<p><strong>If this answer meets your needs please mark the green check beside it to indicate accepted answer. Thanks.</strong></p>
|
9092 | |c++|compile| | How do you call a class method with named parameters? | 2015-03-07T19:01:25.357 | <p>I have a C++ class constructor like:</p>
<pre><code>Motors(int p1=0, int p2=0);
</code></pre>
<p>However, when I attempt to instantiate it with <a href="http://en.wikipedia.org/wiki/Named_parameter" rel="nofollow">named parameters</a> like:</p>
<pre><code>Motors motors(p1=123, p2=456);
</code></pre>
<p>the Arduino C/C++ compiler gives me the errors:</p>
<pre><code>src/motors.ino:3: error: ‘p1’ was not declared in this scope
src/motors.ino:3: error: ‘p2’ was not declared in this scope
</code></pre>
<p>The compiler doesn't seem to support named parameters and thinks I'm referring to variables. I thought named parameters was a pretty widely supported feature, even in C++. What am I doing wrong?</p>
| <p>C++ doesn't support named parameters, and I doubt it ever will.</p>
<p>It has strict calling conventions which mean you couldn't re-order the parameters at call-time without adding an unnecessary layer of data duplication/indirection (which would hurt performance). It would also need a significant change to compiler architecture, as variable/parameter names are usually stripped out long before the linker is invoked.</p>
<p>If you want to achieve a similar effect though, you could use comment blocks instead, e.g.:</p>
<pre><code>Motors motors(/*p1*/ 123, /*p2*/ 456);
</code></pre>
|
9099 | |progmem| | Sketch stops printing after writing a few times | 2015-03-07T21:45:38.540 | <p>I am trying to build a random horoscope printer. I have a series of strings in an array which I am storing in program memory. I then pick a random number and print that index concatenated with a title. But it often (but not always) only runs 4 or 5 times.</p>
<pre><code>#include <avr/pgmspace.h>
const char string_0[] PROGMEM = "You have a great need for other people to like and admire you. ";
const char string_1[] PROGMEM = "You have a tendency to be critical of yourself. ";
const char string_2[] PROGMEM = "You have a great deal of unused capacity which you have not turned to your advantage. ";
const char string_3[] PROGMEM = "While you have some personality weaknesses, you are generally able to compensate for them. ";
const char string_4[] PROGMEM = "Your sexual adjustment has presented problems for you. ";
const char string_5[] PROGMEM = "Disciplined and self-controlled outside, you tend to be worrisome and insecure inside. ";
const char string_6[] PROGMEM = "At times you have serious doubts as to whether you have made the right decision or done the right thing. ";
const char string_7[] PROGMEM = "You prefer a certain amount of change and variety and become dissatisfied when hemmed in by restrictions and limitations. ";
const char string_8[] PROGMEM = "You pride yourself as an independent thinker and do not accept others' statements without satisfactory proof. ";
const char string_9[] PROGMEM = "You have found it unwise to be too frank in revealing yourself to others. ";
const char string_10[] PROGMEM = "At times you are extroverted, affable, sociable, while at other times you are introverted, wary, reserved. ";
const char string_11[] PROGMEM = "Some of your aspirations tend to be pretty unrealistic. ";
const char string_12[] PROGMEM = "Security is one of your major goals in life. ";
const char* const string_table[] PROGMEM = {string_0, string_1, string_2, string_3, string_4, string_5, string_6, string_7, string_8, string_9, string_10, string_11, string_12};
void setup() {
Serial.begin(9600);
randomSeed(analogRead(2));
}
void loop() {
Serial.println("WE GOING TO LOOP NOW");
char buffer[50];
int rand = random(0,12);
Serial.println(rand);
strcpy_P(buffer, (char*)pgm_read_word(&(string_table[rand]))); // Necessary casts and dereferencing, just copy.
char text[15] = "Your horoscope";
String output;
output = strcat(text, buffer);
Serial.println(output);
delay(1000);
}
</code></pre>
<p>I also sometimes don't seem to get very clean results, but I'm not sure why. I.e. printing WWWW... and missing the first part of the string in the serial monitor.</p>
<pre><code>WWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWE GWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWE GOING TO LOOP NOW
1
Your horoscopeYou have a tendency to be critical of yourself.
WE GOING TO LOOP NOW
3
or them. While you have some personality weaknesses, you are generally able to compensate for them.
WE GOING TO LOOP NOW
4
Your horoscopeYour sexual adjustment has presented problems for you.
WE GOING TO LOOP NOW
2
ge. You have a great deal of unused capacity which you have not turned to your advantage.
</code></pre>
| <p>What you see is undefined behavior. You define your buffer to have a length of 50 bytes:</p>
<blockquote>
<p>char buffer[50];</p>
</blockquote>
<p>This is too short for most of the strings you want copy into it and you will thus overwrite other variables.</p>
<p>The simplest solution is to increase the buffer size so that the longest string fits (e.g. 150). You will see that it then works as you expect. Take a look at <a href="http://linux.dd.com.au/wiki/Arduino_Static_Strings" rel="nofollow">http://linux.dd.com.au/wiki/Arduino_Static_Strings</a> for hints how to avoid wasting RAM for the buffer.</p>
|
9106 | |i2c|communication|accelerometer|mpu6050| | How to change i2c address for mpu9250? | 2015-03-08T03:58:15.527 | <p>I'd like to connect 12 mpu9250 sensors to one arduino board.</p>
<p>I can't find documentation on how to change the addresses of mpu9250 boards. (i read through <a href="http://www.invensense.com/mems/gyro/documents/PS-MPU-9250A-01.pdf" rel="nofollow">the reference</a> ). Some tutorials talk about changing addresses for <a href="http://tronixstuff.com/2010/10/29/tutorial-arduino-and-the-i2c-bus-part-two/" rel="nofollow">other device</a> so i assume it is possible for mpu9250. I found <a href="http://www.invensense.com/mems/gyro/documents/RM-MPU-9250A-00.pdf" rel="nofollow">this</a> map of registers but can't figure out how to change the address.</p>
<p>I realize that mpu9250 might be too specific, so general guidance on how to solve these problems would be highly appreciated. </p>
<p>mpu9250 is similar to more popular mpu9150 and mpu6050. It is also known as GY-9250</p>
| <p>Might be a little late, but you can string more than two of these on one I2C bus, with a little ingenuity.</p>
<p>You connect the AD0 pin of each MPU to a different I/O pin of the processor, then take low the address of the one MPU you want to talk to.</p>
<p>Then that MPU has one address, all the others have the other address, and being slaves will not respond.</p>
<p>Provided you don't have more than one MPU selected at once, works a dream.</p>
|
9107 | |wifi|esp8266| | How to get the signal strength of the network connected with the ESP8266 | 2015-03-08T08:21:04.860 | <p>I am using ESP8266 module with Arduino Uno.I don't know how to get the signal strength of the network with which ESP8266 is connected.Please help..</p>
| <p>The page <a href="http://tomeko.net/other/ESP8266/" rel="nofollow">http://tomeko.net/other/ESP8266/</a> names the following command:</p>
<blockquote>
<p>AT+CWLAP // list available access points</p>
</blockquote>
<p>According to the example given there, this returns a list of items looking like this:</p>
<blockquote>
<p>+CWLAP:(3,"UPC784xxx",-75,"70:54:d2:xx:xx:xx",1)</p>
</blockquote>
<p>where <em>"APs are sorted by channel and values are: (security, "name", <strong>signal strength</strong>, MAC, channel) where for security: 0 = open, 1 = WEP, 3 = WPA, 4 = WPA2"</em>.</p>
<p>Thus you can use <code>AT+CWJAP?</code> to obtain the name of the network you're connected to and get the signal strength from the respective item in the list provided by <code>AT+CWLAP</code>.</p>
<p>See <a href="http://wiki.iteadstudio.com/ESP8266_Serial_WIFI_Module" rel="nofollow">http://wiki.iteadstudio.com/ESP8266_Serial_WIFI_Module</a> for a reference of commands.</p>
|
9117 | |arduino-due|c|port-mapping| | SAM3X8E (Arduino Due) Pin IO registers | 2015-03-08T17:45:10.143 | <p>How do the IO registers of Arduino Due work?
On Arduino Uno just set <code>DDRx</code>, then <code>PINx</code> to read, <code>PORTx</code> to write, I'd like to do the same thing with an Arduino Due, but it has many more registers, such as <code>PIO_OWER</code>, <code>PIO_OSER</code>, <code>PIO_CODR</code>, <code>PIO_SODR</code>, etc. I find no correspondence between Arduino Uno and Arduino Due registers.</p>
<p>There are also some useful functions such as <code>pio_clear</code>, <code>pio_set</code>, <code>pio_get</code>, and others, all explained here:</p>
<p><a href="http://asf.atmel.com/docs/3.19.0/sam3x/html/group__sam__drivers__pio__group.html" rel="nofollow noreferrer">http://asf.atmel.com/docs/3.19.0/sam3x/html/group__sam__drivers__pio__group.html</a></p>
<p>Now, I think I've understood what the three mentioned functions do, but not others, for example:</p>
<pre class="lang-cpp prettyprint-override"><code>pio_configure (Pio *p_pio, const pio_type_t ul_type, const uint32_t ul_mask, const uint32_t ul_attribute)
</code></pre>
<p>I can't figure out what <code>ul_attribute</code> and <code>ul_type</code> are.</p>
| <p>I actually followed the above examples and did many tests that I am comfident the results will aid anyone looking into addressing the registers directly.</p>
<pre><code> void setup() {
pinMode(25, OUTPUT);
pinMode(26, OUTPUT);
pinMode(27, OUTPUT);
pinMode(28, OUTPUT);
pinMode(29, OUTPUT);
//REG_PIOD_SODR = 0b00000000000000000000000001001111; // written in binary form
REG_PIOD_SODR = 0x0000004F; //written in Hexadecimal form. Note the differences. Thw two, binary and Hexadecimal are the same.
delayMicroseconds (250000);
//REG_PIOD_CODR = 0b00000000000000000000000001001111;
REG_PIOD_CODR = 0x0000004F;
delayMicroseconds (2000000);
}
void loop()
{
//REG_PIOD_ODSR = 0b00000000000000000000000001001111; // serts all the bits set to 1 HIGH and the rest set to 0 LOW
REG_PIOD_SODR = 0b00000000000000000000000001001111; // sets all the bits set to 1 HIGH and leaves the rest untouched
delay(500);
REG_PIOD_CODR = 0b00000000000000000000000000000100;//1
//REG_PIOD_CODR = 0x00000004; //identical to the line above only that it is in Hexadecimal format
//REG_PIOD_SODR = 0b00000000000000000000000000000100; // will disable the rest bits and leave only one HIGH
delay(500);
REG_PIOD_CODR = 0b00000000000000000000000000000010;//2
delay(500);
REG_PIOD_CODR = 0b00000000000000000000000001000000;//3
delay(500);
REG_PIOD_CODR = 0b00000000000000000000000000001000; //4
delay(500);
REG_PIOD_CODR = 0b00000000000000000000000000000001; //5
delay(500);
}
</code></pre>
<p>To explain better, all pins desired to be <strong>OUTPUTs</strong> are set via pinMode and then, it is very optional toenable them while at SETUP. In this case, I just wanted the pins to be made HIGH just once while at SETUP and then LOW before the loop starts. I've used REG_PIO?_SODR (<strong>in this case, ? is port D so it is REG_PIOD_SODR</strong>) which only make its set to 1 HIGH and the rest are left untouched. I have used both in binary and Hexadecimal format. Binary makes it easier to identify which pins to enable. For instance, bit PD0 is the right most bit in the binary number. It starts from Right going to left. For example, 0b00000000000000000000000000000001, bit 1 is PD0, PD1 will be 0b00000000000000000000000000000010 and so on.
You've seen examples provided in this format, <strong>0xfffffffd</strong> the <strong>x</strong> means it is in hexadecimal format and <strong>b</strong> is in binary format. To convert binary to Hexadecimal, youcan use the easiest route via this <a href="https://byjus.com/maths/convert-hexadecimal-to-binary/" rel="nofollow noreferrer">link</a></p>
<p>To explain, any Hexadecimal number represents 4 binary numbers, example, Hex 0 is binary 0000, Hex F is binary 1111, Hex 4 is binary 0100, Hex A is binary 1010.</p>
<p>Now that is understood, going to the main loop, I have used the <strong>REG_PIOD_SODR</strong> because it gives one the freedom to address the pins one wants without touching any other pins on that port. You can use <strong>REG_PIOD_ODSR</strong> ONLY when you want to set all bits at once. This is ideal when you want many pins set HIGH and/or LOW at once. It is not the best if you want to set just a few pins HIGH/LOW and leave the rest untouched. <strong>REG_PIOD_SODR</strong> is ideal when some pins needs to be left untouched. You don't want to set one bit HIGH then all pins are HIGH. This command <strong>REG_PIOD_CODR</strong> sets the bits set 1 LOW and leave all the rest set to 0 untouched.</p>
<p>This code simply makes the bits selected at setup HIGH for the said time in delay then LOW for the given time. In loop, all bits selected as 1 are made HIGH and the rest untouched. The following lines simply turn the selected bits LOW one at a time until all are OFF and then the process repeats.</p>
<p>I hope this oversimplified explanation aided someone.</p>
|
9118 | |arduino-uno|serial|programming|networking|tcpip| | Arduino TCP communication with Android phone | 2015-03-08T18:02:43.140 | <p>I am trying to communicate Arduino Uno with an android phone. What I trying to is:</p>
<ol>
<li><p>Android device post a string to Arduino</p></li>
<li><p>Arduino post a integer to Android</p></li>
</ol>
<p>So far I can post message from Android, received in Arduino board, but I <strong>can not post a integer to Android, nothing receive at Android</strong></p>
<p><strong>Arduino Code</strong> (Which can receive character "a", "b", "c", "d", and for case "z", I would like to send back the distance which is an <code>int</code>) : </p>
<pre><code>void loop()
{
distance = Dist.getDistanceCentimeter();
if(distance<=5 & distance>1)
{
back();
delay(100);
ting();
distance=0;
}
if(Serial.available())
{
lkf = Serial.read();
switch(lkf)
{
case 'a':
front();
servoX.write(90);
lkf=0;
break;
case 'b':
back();
lkf=0;
break;
case 'c':
left();
lkf=0;
break;
case 'd':
right();
lkf=0;
break;
case 'z':
Serial.write(distance);
break;
}
}
}
</code></pre>
<p><strong>Android Code:</strong></p>
<p><strong>In Main Activity</strong></p>
<pre><code>@Override
protected TCPClient doInBackground(String... message) {
//create TCPClient object
mTcpClient = new TCPClient(new TCPClient.OnMessageReceived() {
@Override
//check whether server return message
public void messageReceived(String message) {
f_sensor.setText(message);
Log.d("test1","msg rece" + message);
//publishProgress(message);
}
});
mTcpClient.run();
return null;
}
</code></pre>
<p><strong>TCP Cilent</strong></p>
<pre><code>public class TCPClient {
private String serverMessage;
public static final String SERVERIP = "192.168.8.1"; //your computer IP address
public static final int SERVERPORT = 2001;
private OnMessageReceived mMessageListener = null;
private boolean mRun = false;
PrintWriter out;
BufferedReader in;
/**
* Constructor of the class. OnMessagedReceived listens for the messages received from server
*/
public TCPClient(OnMessageReceived listener) {
mMessageListener = listener;
}
/**
* Sends the message entered by client to the server
* @param message text entered by client
*/
public void sendMessage(String message){
if (out != null && !out.checkError()) {
out.println(message);
out.flush();
}
}
public void stopClient(){
mRun = false;
}
public void run() {
mRun = true;
try {
//here you must put your computer's IP address.
InetAddress serverAddr = InetAddress.getByName(SERVERIP);
Log.e("TCP Client", "C: Connecting...");
//create a socket to make the connection with the server
Socket socket = new Socket(serverAddr, SERVERPORT);
try {
//send the message to the server
out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true);
Log.e("TCP Client", "C: Sent.");
Log.e("TCP Client", "C: Done.");
//receive the message which the server sends back
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
//in this while the client listens for the messages sent by the server
while (mRun) {
serverMessage = in.readLine();
if (serverMessage != null && mMessageListener != null) {
//call the method messageReceived from MyActivity class
mMessageListener.messageReceived(serverMessage);
}
serverMessage = null;
}
Log.d("test1",serverMessage);
Log.e("RESPONSE FROM SERVER", "S: Received Message: '" + serverMessage + "'");
} catch (Exception e) {
Log.e("TCP", "S: Error", e);
} finally {
//the socket must be closed. It is not possible to reconnect to this socket
// after it is closed, which means a new socket instance has to be created.
socket.close();
}
} catch (Exception e) {
Log.e("TCP", "C: Error", e);
}
}
//Declare the interface. The method messageReceived(String message) will must be implemented in the MyActivity
//class at on asynckTask doInBackground
public interface OnMessageReceived {
public void messageReceived(String message);
}
}
</code></pre>
| <p>Using <code>serial.println</code> instead of <code>serial.write</code> fixes the issue.</p>
|
9119 | |arduino-mega|rfid|icsp| | Can I connect an RFID reader to the ICSP header? | 2015-03-08T18:59:31.437 | <p>I am connecting an RFID reader to my Arduino mega. The directions that I have found say that I need to use pins 50-53. I also noticed that the ICSP header contains (what looks like) a secondary connection to these pins: </p>
<p><a href="http://arduino.cc/en/Reference/SPI" rel="nofollow">http://arduino.cc/en/Reference/SPI</a></p>
<p>Can I connect my RFID reader to the ICSP header:</p>
| <p>Yes you can. However the SS isn't present on that header. You can however use any pin you want for SS (if the library you use supports it, that is)</p>
|
9143 | |communication| | Can you connect an output pin from one Arduino to the input pin of another? | 2015-03-08T20:15:43.150 | <p>I have a system that uses two Arduino boards. One is used to control several different functions, and the other is dedicated to driving a 45 second countdown display (comprised of two large 7 segment displays.) All this second Arduino needs is a single signal to tell it when to start. I would like to simply connect an output pin (on #1) to an input pin (on #2) and and send a single pulse to get the clock started. Fo something this simple, I wanted to avoid using I2C. Can I do this? If so, is there anything else I need to be aware of (like connecting ground to ground?)</p>
| <p>Yes, you can. That is indeed the most easy way of communication.</p>
<p>And like you said, you have to connect the grounds of both arduino's. </p>
<p>Optionally you could add a pull-up of pull-down resistor, so the countdown doesn't accidentally start if the first arduino is still starting up, or is disconnected.</p>
|
9146 | |arduino-uno|c++| | snprintf crashing my program | 2015-03-08T21:43:19.307 | <p>I have to admit that I can't really use this function.</p>
<p>I'm trying to format some json but it crashing all the time my arduino:</p>
<pre><code>char response[300];
tmp = "123";
snprintf(response, 300, "[{Name:'Furnace',Value=%s,Alarm={MinValue=%s,MaxValue=%s}},{Name:'Room',Value=%s,Alarm={MinValue=%s,MaxValue=%s}}]", tmp);
</code></pre>
<p>How should I use this function properly?</p>
|
<pre class="lang-c prettyprint-override"><code>char response[300];
tmp = "123";
snprintf(response, 300,
"[{Name:'Furnace',Value=%s,Alarm={MinValue=%s,MaxValue=%s}},"
"{Name:'Room',Value=%s,Alarm={MinValue=%s,MaxValue=%s}}]",
tmp, tmp, tmp, tmp, tmp, tmp);
</code></pre>
<p>In other words, you should add, after the format string, as many extra
parameters as there are %s in the format string.</p>
<p>PS: This looks like JSON, but it is not really valid JSON.
The format below should give valid JSON:</p>
<pre class="lang-c prettyprint-override"><code>"[{\"Name\":\"Furnace\",\"Value\":%s,"
"\"Alarm\":{\"MinValue\":%s,\"MaxValue\":%s}},"
"{\"Name\":\"Room\",\"Value\":%s,"
"\"Alarm\":{\"MinValue\":%s,\"MaxValue\":%s}}]",
</code></pre>
|
9156 | |arduino-uno|bootloader|arduino-nano|isp| | Burning a Uno bootloader into a Nano | 2015-03-09T13:27:54.187 | <p>I bought some cheap Arduino Nanos from ebay, but the watchdog does not work in them.</p>
<p>So I removed their old bootloader and burnt a new Nano bootloader from the Arduino IDE. Same problem, the watchdog didn't work.</p>
<p>Then, I burned a Uno bootloader to the Arduino Nano and now the watchdog works properly. The only issue here is that in Arduino IDE I now have to tell it that I am programming an Arduino Uno instead of a Nano. So far everything seems to work just fine.</p>
<p>Are there other problems that may arise from using a Uno bootloader in a Nano? I notice that there are some extra analog pins in Arduino Nano, but I will still be able to use them with the Arduino Uno bootloader right?</p>
| <p>In boards.txt in the Uno section, you change one line for the pinout type from uno.standard to all_pins or something like that to make the analog inputs A6 & A7 available. Compare the standard Nano line against the Uno line and you can see the difference. I can't access the Arduino files from here to say what they are specifically, sorry.</p>
<p>Ok, here we go:</p>
<p>Uno
uno.build.variant=standard</p>
<p>Nano
nano.build.variant=eightanaloginputs</p>
<p>So change the Uno line to
uno.build.variant=eightanaloginputs</p>
<p>Then you can bootlood the Nano board with Uno bootloader and should have A6, A7 available without issue.</p>
|
9161 | |analogread| | Do I need to worry about voltage, coming from ground, and effecting an analog input? | 2015-03-09T15:40:44.420 | <p>I am building a project that includes an analog Input and several digital Inputs and Outputs. All of them connect to ground in some way. Do I need to worry about voltage, coming from the digital outputs, going to ground, and effecting readings on the analog input? If so, how do I deal with this?</p>
| <p>In this case I do not believe ground bounce will be a problem. I normally only encounter it on high speed PCB designs. You will get noise from the power supply(s). Any impedance induced between the ground of analog input (circuit board ground) and the sensor will give you problems. Be sure all grounds are low impedance in nature. Since you are designing the project consider and I assume a PCB, filtering the Aref pin supply with a small cap and a 100 ohm resistor. A low pass filter on all inputs will help, a small cap from the input pin to ground and feed it via a resistor. Good capacitors are very important.</p>
|
9163 | |arduino-uno|wifi| | Using Arduino for Industrial process | 2015-03-09T16:18:58.043 | <p>I was wondering if the Arduino is applicable for Industrial monitoring, I want to make a real time status of the presses in our company. I haven't seen or read much about people using Arduino at an Industrial level, most of what I have seen or read are prototype projects.
I'm new in electronics and don't know if there is a better way of doing this rather than using Arduino. I was thinking of using Arduino Uno and Arduino Ethernet Shield or Wifi Shield.</p>
<p>Any help on some information on how to start on this is helpful.</p>
| <p>Industruino just came out a couple days ago: </p>
<ol>
<li><a href="https://blog.arduino.cc/2015/09/21/industruino-makes-industrial-automation-easy-now-atheart/" rel="noreferrer">https://blog.arduino.cc/2015/09/21/industruino-makes-industrial-automation-easy-now-atheart/</a> </li>
<li><a href="https://industruino.com/page/home" rel="noreferrer">https://industruino.com/page/home</a> </li>
<li><a href="https://www.youtube.com/watch?t=200&v=MhE1zlwsUu0" rel="noreferrer">https://www.youtube.com/watch?t=200&v=MhE1zlwsUu0</a> </li>
<li><a href="https://industruino.com/shop/product/industruino-ind-i-o-kit-2" rel="noreferrer">https://industruino.com/shop/product/industruino-ind-i-o-kit-2</a> </li>
</ol>
<p>Also:<br>
1. <a href="http://www.rugged-circuits.com/ruggeduino/" rel="noreferrer">Ruggeduino</a> has much better pin protection than a standard Arduino.</p>
<p>One of the above may meet your need. </p>
<p>(No, I am not affiliated in any way with the above links; I just saw the Industruino the other day on the Arduino website and wanted to point out a couple other options).</p>
|
9165 | |serial| | Arduino Sainsmart uno communication problem | 2015-03-09T16:09:50.237 | <p>I'm trying to communicate with my arduino uno but it seems to have troubles to understand characters. For example, printing things with Serial display weird things, changes characters, removes some. </p>
<p>For exemple printing "test !" every two seconds results in that : </p>
<p><img src="https://i.stack.imgur.com/aLxDB.png" alt="enter image description here"></p>
<p>Every characters have been removed except "!"...</p>
<p>Is my arduino broken ? Thanks in advance</p>
| <p>You are doing 2 things wrong in your program:</p>
<p>First is using serial.write(), which writes bytes rather than ASCII.</p>
<p>Second is you are declaring a string literal as a char instead, you must declare a string using double quotation marks (which is ") so that your program should read:</p>
<pre><code>Serial.print("Test!");
</code></pre>
<p>When you declare 'Test !' you are doing it wrong, and it will only take the last char in the string, which is '!' - using single quote marks is for a single char declaration, like '!' or 'T', and you can make an array of chars into a string if you wanted, like this:</p>
<pre><code>char array[] = {'T', 'E', 'S', 'T', '!' };
Serial.write(array, 5);
</code></pre>
<p>but why would you when the earlier one works better?</p>
|
9167 | |arduino-uno|xbee|atmega328| | RSSI stop sketch on a gboard (atmega) | 2015-03-09T16:39:41.733 | <p>I have this function in my code and works fine (it returns a valid value, I put this value into a int variable outside function), but when end the function (or continue the code), my sketch stop/die...</p>
<pre><code>///FUNCION PARA RSSI XBEE///
byte rss() { ///PARA RSSI
union {byte B; char C;} atCmd[3];
AtCommandRequest atCmdReq;
AtCommandResponse atResp;
byte respLen, *resp, dBm;
strcpy(&atCmd[0].C, "DB");
atCmdReq = AtCommandRequest(&atCmd[0].B);
atResp = AtCommandResponse();
xbee.send(atCmdReq);
if (xbee.readPacket(5000)) {
if (xbee.getResponse().getApiId() == AT_COMMAND_RESPONSE) {
xbee.getResponse().getAtCommandResponse(atResp);
if (atResp.isOk()) {
respLen = atResp.getValueLength();
if (respLen == 1) {
resp = atResp.getValue();
dBm = resp[0];
return dBm;
}
else {
// Serial.println("Unexpected response");
}
}
else {
// Serial.println("ERROR");
}
}
else {
// Serial.println("Unknown response");
}
}
else {
// Serial.println("No response");
}
}///fin rss()
</code></pre>
<p>¿Any tips?</p>
| <p>Your function is only returning a value when everything works OK. If an error occurs, the problem is reported to serial but it doesn't return anything. It seems likely that this could cause stack corruption which could make the program stop.</p>
<p>A simple solution would be to put <code>return 0;</code> (or some other number) just before the end of the function.</p>
|
9171 | |arduino-uno|serial|sensors|pins|arduino-ide| | How to add Ultrasonic Sensor to the board? | 2015-03-09T17:11:26.910 | <p>I am making an RC car , have combined the <strong>Arduino UNO R3</strong> with the <strong>AR 293d</strong>, and pluged in the HC-SR04 sensor to the SRO4 hole at the left top corner in the below graph. However, besides one sensor I <strong>would like to add three more HC-SR04 sensor</strong>.</p>
<p>Reference:
<a href="http://www.instructables.com/id/Simple-Arduino-and-HC-SR04-Example/" rel="nofollow noreferrer">http://www.instructables.com/id/Simple-Arduino-and-HC-SR04-Example/</a></p>
<p><img src="https://i.stack.imgur.com/6TtmL.png" alt="enter image description here"></p>
<p>The problems are</p>
<p>1) is the board sufficient to plug three more sensor ? </p>
<p>2) or what extra board I need if not sufficient and how to combine those board</p>
<p>2) also, can I plug in other hole?</p>
<p>Thanks for helping</p>
<p><strong>Update: breadboard connection</strong></p>
<p>So I have to get a stuff like this?</p>
<p><a href="http://www.tandyonline.co.uk/small-solderless-breadboard.html" rel="nofollow noreferrer">http://www.tandyonline.co.uk/small-solderless-breadboard.html</a></p>
<p>and one more question, sorry for begin newbie, there are many holes on breadboard, which hole I should connect those three sensor on it, and the hold I should connect the breadboard with the AR-293D board?</p>
<p>And for programming, is there any way to get the pin at the breadboard as I have read some program before, the pin is assign with a number? </p>
<p>Thanks again for helping.</p>
<p><img src="https://i.stack.imgur.com/hni7b.png" alt="enter image description here"></p>
| <p>1) Not really. You have so little space and you have to selder them. Try using wires</p>
<p>2) If you want it to be flexible use a sandard solderless breadoard on the center of the car and then with male-female jumperwires try connecting them. </p>
<p>3) The board has traces. That means some holes have a very specific purpose.</p>
<h2>Updated:</h2>
<p>On every breadboard the holes are connected verticaly. For example, in the image from your breadboard you posted 1A, 1B, 1C, 1D and 1E are connected together.
If you would like to have all of the 3 sensors better use wires and then atach them on to your breadboard.</p>
<p>Here is a picture:
<a href="https://www.dropbox.com/s/3ij4w6eytio8p08/Screen%2016-25-31.png?dl=0" rel="nofollow">https://www.dropbox.com/s/3ij4w6eytio8p08/Screen%2016-25-31.png?dl=0</a></p>
|
9174 | |serial|softwareserial| | Serial Print, String And Variable On Same Line | 2015-03-09T18:01:04.697 | <p>How can I print to the serial monitor a string or just single character followed by a variable like "L 55"</p>
| <p>Thanks a lot for your answers. I made this ... </p>
<pre><code>#define DEBUG //If you comment this line, the functions below are defined as blank lines.
#ifdef DEBUG //Macros
#define Say(var) Serial.print(#var"\t") //debug print, do not need to put text in between of double quotes
#define SayLn(var) Serial.println(#var) //debug print with new line
#define VSay(var) Serial.print(#var " =\t"); Serial.print(var);Serial.print("\t") //variable debug print
#define VSayLn(var) Serial.print(#var " =\t"); Serial.println(var) //variable debug print with new line
#else
#define Say(...) //now defines a blank line
#define SayLn(...) //now defines a blank line
#define VSay(...) //now defines a blank line
#define VSayLn(...) //now defines a blank line
#endif
</code></pre>
|
9175 | |pins|atmega328|system-design| | ATMega328P-PU and 328P-AU | 2015-03-09T18:23:24.873 | <p>im planing to make my very own arduino design based on the Arduino PRO mini. I picked this board instead of the UNO mostly because it's way more simpler compared with the UNO since the USB-to-Serial part is missing. As many of you know the MINI uses the 328P-AU which is the SMD version of the 328P however since the AU version is too small for me i would like to use the PU (UNO's chip) instead. From the datasheets the only difference is a small change in the pins position. And the one million dollar question is: Is there any difference on those 2 chips? If i try to use the same design just with the PU model is it gonna work?</p>
| <p>The <code>-AU</code> and <code>-PU</code> suffixes on the part name indicate different packages. The former is used for the "32A" package (32-lead TQFP), and the latter is used for the "28P3" package (28-lead DIP). In plain English, the <code>-AU</code> is a surface-mount part, and the <code>-PU</code> is a breadboard-friendly chip.</p>
<p>As far as functionality, there is virtually no difference. The 32A package exposes pins for ADC6 and ADC7, which are not available on the 28P3 package, but they are otherwise identical. (Note that these pins are <em>only</em> used for the ADCs; they are not a member of any port, and thus cannot be used for digital I/O.)</p>
|
9183 | |digital| | For the digital output pins, how is LOW different than no connection? | 2015-03-09T22:26:29.240 | <p>I am working with relays and I noticed that connecting the trigger pin to ground (or a digital pin set to LOW) is not the same as having the trigger connected to anything. For the digital output pins, how is LOW different than no connection? Is there actually a current flowing into the LOW pin, or is there a tiny current flowing into the relay?</p>
<p>Is Ground and LOW the same voltage? </p>
| <p><em>(Edit for clarification: I've assumed in this answer that you're asking about the difference between connecting the relay to ground/LOW vs. connecting the relay to nothing at all. I've also assumed by the word "trigger" that your relay has some kind of digital actuation built-in, such as a transistor, or that it's simply a Solid State Relay.)</em></p>
<p>If something is unconnected, it is described as 'floating'. This means there could be random voltage spikes in it caused by nearby electromagnetic fields, making it appear to be switching on/off.</p>
<p>Connecting something to ground or LOW can stop this from happening by drawing away any induced currents.</p>
|
9189 | |sensors|library|arduino-galileo|node.js|johnny-five| | NodeJS (Galileo-IO) + Arduino sensor library | 2015-03-10T05:30:00.517 | <p>I've done some basic apps with NodeJS firmata where I can connect to my Arduino Uno and do the basics like reading a pin or doing a servo write. I'd like to go further and play with some different sensors from vendors like Adafruit. </p>
<p>Many such sensors appear to come with their own Arduino libraries. Using NodeJS firmata to communicate with my Uno, could I somehow use the sensor libraries? Maybe by including their header files in the Standard Firmata sketch before uploading or...? But then I don't know how I'd get at their methods from my NodeJS app. </p>
<p>Even better, I'd love a little direction on how to go about using an Arduino sensor library in a sketch, and use Galileo-IO to interact with the sensor that way, if possible.</p>
| <p>Including the header files for the libraries in the standard Firmata
sketch is only the first step. You will have to also modify the sketch in
order to actually <em>use</em> the libraries. You will have to figure out a way
of interacting with the libraries through the Firmata protocol and
implement this in your modified version of the sketch. You will then
have to modify the JavaScript side to enable these new interactions.
That's where you will write the missing methods</p>
|
9192 | |arduino-uno| | Arduino on ubuntu 14.4 gives "Broken pipe" and "Input/output error" | 2015-03-10T09:46:43.117 | <p>Im using arduino (R2) uno board and my pc is running 64bit ubuntu 14.4.
I was previously using arduino on ubuntu 10.04 for a long time and got no error. I recently moved to 14.4 from 10.4.</p>
<p>I installed arduino using this command</p>
<pre><code>$ sudo apt-get update && sudo apt-get install arduino arduino-core
</code></pre>
<p>later arduino appeared, but was not working. According to <a href="http://vishnuvarkala.blogspot.in/2012/07/arduino-ide-not-detecting-serial-port.html" rel="nofollow">this link</a>, i was able to launch the IDE on mouse click. I then tried to upload servo examples, i get following errors.</p>
<pre><code>Binary sketch size: 1,056 bytes (of a 32,256 byte maximum)
ioctl("TIOCMSET"): Broken pipe
ioctl("TIOCMGET"): Input/output error
</code></pre>
<p>I get the same error for even an Led blinking program too.</p>
<p><strong>Update 1:</strong> (after Edgar's comment)</p>
<p>on terminal i get</p>
<pre><code>~$ /usr/share/arduino/hardware/tools/avr/bin/avr-g++ -c -g -Os -Wall -fno-exceptions -ffunction-sections -fdata-sections -mmcu=atmega328p -DF_CPU=16000000L -MMD -DUSB_VID=null -DUSB_PID=null -DARDUINO=105 -D__PROG_TYPES_COMPAT__ -I/usr/share/arduino/hardware/arduino/cores/arduino -I/usr/share/arduino/hardware/arduino/variants/standard -I/usr/share/arduino/libraries/Servo /tmp/build4933543797518254688.tmp/Sweep.cpp -o /tmp/build4933543797518254688.tmp/Sweep.cpp.o
avr-g++: error: /tmp/build4933543797518254688.tmp/Sweep.cpp: No such file or directory
avr-g++: fatal error: no input files
compilation terminated.
</code></pre>
<p>But on the IDE, after enabling verbos i get</p>
<pre><code>/usr/share/arduino/hardware/tools/avr/bin/avr-g++ -c -g -Os -Wall -fno-exceptions -ffunction-sections -fdata-sections -mmcu=atmega328p -DF_CPU=16000000L -MMD -DUSB_VID=null -DUSB_PID=null -DARDUINO=105 -D__PROG_TYPES_COMPAT__ -I/usr/share/arduino/hardware/arduino/cores/arduino -I/usr/share/arduino/hardware/arduino/variants/standard -I/usr/share/arduino/libraries/Servo /tmp/build4933543797518254688.tmp/Sweep.cpp -o /tmp/build4933543797518254688.tmp/Sweep.cpp.o
/usr/share/arduino/hardware/tools/avr/bin/avr-g++ -c -g -Os -Wall -fno-exceptions -ffunction-sections -fdata-sections -mmcu=atmega328p -DF_CPU=16000000L -MMD -DUSB_VID=null -DUSB_PID=null -DARDUINO=105 -D__PROG_TYPES_COMPAT__ -I/usr/share/arduino/hardware/arduino/cores/arduino -I/usr/share/arduino/hardware/arduino/variants/standard -I/usr/share/arduino/libraries/Servo -I/usr/share/arduino/libraries/Servo/utility /usr/share/arduino/libraries/Servo/Servo.cpp -o /tmp/build4933543797518254688.tmp/Servo/Servo.cpp.o
/usr/share/arduino/hardware/tools/avr/bin/avr-gcc -c -g -Os -Wall -ffunction-sections -fdata-sections -mmcu=atmega328p -DF_CPU=16000000L -MMD -DUSB_VID=null -DUSB_PID=null -DARDUINO=105 -D__PROG_TYPES_COMPAT__ -I/usr/share/arduino/hardware/arduino/cores/arduino -I/usr/share/arduino/hardware/arduino/variants/standard /usr/share/arduino/hardware/arduino/cores/arduino/wiring_analog.c -o /tmp/build4933543797518254688.tmp/wiring_analog.c.o
/usr/share/arduino/hardware/tools/avr/bin/avr-gcc -c -g -Os -Wall -ffunction-sections -fdata-sections -mmcu=atmega328p -DF_CPU=16000000L -MMD -DUSB_VID=null -DUSB_PID=null -DARDUINO=105 -D__PROG_TYPES_COMPAT__ -I/usr/share/arduino/hardware/arduino/cores/arduino -I/usr/share/arduino/hardware/arduino/variants/standard /usr/share/arduino/hardware/arduino/cores/arduino/avr-libc/malloc.c -o /tmp/build4933543797518254688.tmp/malloc.c.o
/usr/share/arduino/hardware/tools/avr/bin/avr-gcc -c -g -Os -Wall -ffunction-sections -fdata-sections -mmcu=atmega328p -DF_CPU=16000000L -MMD -DUSB_VID=null -DUSB_PID=null -DARDUINO=105 -D__PROG_TYPES_COMPAT__ -I/usr/share/arduino/hardware/arduino/cores/arduino -I/usr/share/arduino/hardware/arduino/variants/standard /usr/share/arduino/hardware/arduino/cores/arduino/avr-libc/realloc.c -o /tmp/build4933543797518254688.tmp/realloc.c.o
/usr/share/arduino/hardware/tools/avr/bin/avr-gcc -c -g -Os -Wall -ffunction-sections -fdata-sections -mmcu=atmega328p -DF_CPU=16000000L -MMD -DUSB_VID=null -DUSB_PID=null -DARDUINO=105 -D__PROG_TYPES_COMPAT__ -I/usr/share/arduino/hardware/arduino/cores/arduino -I/usr/share/arduino/hardware/arduino/variants/standard /usr/share/arduino/hardware/arduino/cores/arduino/wiring_digital.c -o /tmp/build4933543797518254688.tmp/wiring_digital.c.o
/usr/share/arduino/hardware/tools/avr/bin/avr-gcc -c -g -Os -Wall -ffunction-sections -fdata-sections -mmcu=atmega328p -DF_CPU=16000000L -MMD -DUSB_VID=null -DUSB_PID=null -DARDUINO=105 -D__PROG_TYPES_COMPAT__ -I/usr/share/arduino/hardware/arduino/cores/arduino -I/usr/share/arduino/hardware/arduino/variants/standard /usr/share/arduino/hardware/arduino/cores/arduino/wiring_pulse.c -o /tmp/build4933543797518254688.tmp/wiring_pulse.c.o
/usr/share/arduino/hardware/tools/avr/bin/avr-gcc -c -g -Os -Wall -ffunction-sections -fdata-sections -mmcu=atmega328p -DF_CPU=16000000L -MMD -DUSB_VID=null -DUSB_PID=null -DARDUINO=105 -D__PROG_TYPES_COMPAT__ -I/usr/share/arduino/hardware/arduino/cores/arduino -I/usr/share/arduino/hardware/arduino/variants/standard /usr/share/arduino/hardware/arduino/cores/arduino/wiring.c -o /tmp/build4933543797518254688.tmp/wiring.c.o
/usr/share/arduino/hardware/tools/avr/bin/avr-gcc -c -g -Os -Wall -ffunction-sections -fdata-sections -mmcu=atmega328p -DF_CPU=16000000L -MMD -DUSB_VID=null -DUSB_PID=null -DARDUINO=105 -D__PROG_TYPES_COMPAT__ -I/usr/share/arduino/hardware/arduino/cores/arduino -I/usr/share/arduino/hardware/arduino/variants/standard /usr/share/arduino/hardware/arduino/cores/arduino/wiring_shift.c -o /tmp/build4933543797518254688.tmp/wiring_shift.c.o
/usr/share/arduino/hardware/tools/avr/bin/avr-gcc -c -g -Os -Wall -ffunction-sections -fdata-sections -mmcu=atmega328p -DF_CPU=16000000L -MMD -DUSB_VID=null -DUSB_PID=null -DARDUINO=105 -D__PROG_TYPES_COMPAT__ -I/usr/share/arduino/hardware/arduino/cores/arduino -I/usr/share/arduino/hardware/arduino/variants/standard /usr/share/arduino/hardware/arduino/cores/arduino/WInterrupts.c -o /tmp/build4933543797518254688.tmp/WInterrupts.c.o
/usr/share/arduino/hardware/tools/avr/bin/avr-g++ -c -g -Os -Wall -fno-exceptions -ffunction-sections -fdata-sections -mmcu=atmega328p -DF_CPU=16000000L -MMD -DUSB_VID=null -DUSB_PID=null -DARDUINO=105 -D__PROG_TYPES_COMPAT__ -I/usr/share/arduino/hardware/arduino/cores/arduino -I/usr/share/arduino/hardware/arduino/variants/standard /usr/share/arduino/hardware/arduino/cores/arduino/Stream.cpp -o /tmp/build4933543797518254688.tmp/Stream.cpp.o
/usr/share/arduino/hardware/tools/avr/bin/avr-g++ -c -g -Os -Wall -fno-exceptions -ffunction-sections -fdata-sections -mmcu=atmega328p -DF_CPU=16000000L -MMD -DUSB_VID=null -DUSB_PID=null -DARDUINO=105 -D__PROG_TYPES_COMPAT__ -I/usr/share/arduino/hardware/arduino/cores/arduino -I/usr/share/arduino/hardware/arduino/variants/standard /usr/share/arduino/hardware/arduino/cores/arduino/HID.cpp -o /tmp/build4933543797518254688.tmp/HID.cpp.o
/usr/share/arduino/hardware/tools/avr/bin/avr-g++ -c -g -Os -Wall -fno-exceptions -ffunction-sections -fdata-sections -mmcu=atmega328p -DF_CPU=16000000L -MMD -DUSB_VID=null -DUSB_PID=null -DARDUINO=105 -D__PROG_TYPES_COMPAT__ -I/usr/share/arduino/hardware/arduino/cores/arduino -I/usr/share/arduino/hardware/arduino/variants/standard /usr/share/arduino/hardware/arduino/cores/arduino/Print.cpp -o /tmp/build4933543797518254688.tmp/Print.cpp.o
/usr/share/arduino/hardware/tools/avr/bin/avr-g++ -c -g -Os -Wall -fno-exceptions -ffunction-sections -fdata-sections -mmcu=atmega328p -DF_CPU=16000000L -MMD -DUSB_VID=null -DUSB_PID=null -DARDUINO=105 -D__PROG_TYPES_COMPAT__ -I/usr/share/arduino/hardware/arduino/cores/arduino -I/usr/share/arduino/hardware/arduino/variants/standard /usr/share/arduino/hardware/arduino/cores/arduino/WMath.cpp -o /tmp/build4933543797518254688.tmp/WMath.cpp.o
/usr/share/arduino/hardware/tools/avr/bin/avr-g++ -c -g -Os -Wall -fno-exceptions -ffunction-sections -fdata-sections -mmcu=atmega328p -DF_CPU=16000000L -MMD -DUSB_VID=null -DUSB_PID=null -DARDUINO=105 -D__PROG_TYPES_COMPAT__ -I/usr/share/arduino/hardware/arduino/cores/arduino -I/usr/share/arduino/hardware/arduino/variants/standard /usr/share/arduino/hardware/arduino/cores/arduino/CDC.cpp -o /tmp/build4933543797518254688.tmp/CDC.cpp.o
/usr/share/arduino/hardware/tools/avr/bin/avr-g++ -c -g -Os -Wall -fno-exceptions -ffunction-sections -fdata-sections -mmcu=atmega328p -DF_CPU=16000000L -MMD -DUSB_VID=null -DUSB_PID=null -DARDUINO=105 -D__PROG_TYPES_COMPAT__ -I/usr/share/arduino/hardware/arduino/cores/arduino -I/usr/share/arduino/hardware/arduino/variants/standard /usr/share/arduino/hardware/arduino/cores/arduino/new.cpp -o /tmp/build4933543797518254688.tmp/new.cpp.o
/usr/share/arduino/hardware/tools/avr/bin/avr-g++ -c -g -Os -Wall -fno-exceptions -ffunction-sections -fdata-sections -mmcu=atmega328p -DF_CPU=16000000L -MMD -DUSB_VID=null -DUSB_PID=null -DARDUINO=105 -D__PROG_TYPES_COMPAT__ -I/usr/share/arduino/hardware/arduino/cores/arduino -I/usr/share/arduino/hardware/arduino/variants/standard /usr/share/arduino/hardware/arduino/cores/arduino/HardwareSerial.cpp -o /tmp/build4933543797518254688.tmp/HardwareSerial.cpp.o
/usr/share/arduino/hardware/arduino/cores/arduino/HardwareSerial.cpp: In function ‘void store_char(unsigned char, ring_buffer*)’:
/usr/share/arduino/hardware/arduino/cores/arduino/HardwareSerial.cpp:100:20: warning: comparison between signed and unsigned integer expressions [-Wsign-compare]
if (i != buffer->tail) {
^
/usr/share/arduino/hardware/arduino/cores/arduino/HardwareSerial.cpp: In function ‘void __vector_18()’:
/usr/share/arduino/hardware/arduino/cores/arduino/HardwareSerial.cpp:129:21: warning: unused variable ‘c’ [-Wunused-variable]
unsigned char c = UDR0;
^
/usr/share/arduino/hardware/arduino/cores/arduino/HardwareSerial.cpp: In member function ‘void HardwareSerial::begin(long unsigned int, byte)’:
/usr/share/arduino/hardware/arduino/cores/arduino/HardwareSerial.cpp:370:11: warning: unused variable ‘current_config’ [-Wunused-variable]
uint8_t current_config;
^
/usr/share/arduino/hardware/arduino/cores/arduino/HardwareSerial.cpp: In member function ‘virtual size_t HardwareSerial::write(uint8_t)’:
/usr/share/arduino/hardware/arduino/cores/arduino/HardwareSerial.cpp:469:27: warning: comparison between signed and unsigned integer expressions [-Wsign-compare]
while (i == _tx_buffer->tail)
^
/usr/share/arduino/hardware/tools/avr/bin/avr-g++ -c -g -Os -Wall -fno-exceptions -ffunction-sections -fdata-sections -mmcu=atmega328p -DF_CPU=16000000L -MMD -DUSB_VID=null -DUSB_PID=null -DARDUINO=105 -D__PROG_TYPES_COMPAT__ -I/usr/share/arduino/hardware/arduino/cores/arduino -I/usr/share/arduino/hardware/arduino/variants/standard /usr/share/arduino/hardware/arduino/cores/arduino/main.cpp -o /tmp/build4933543797518254688.tmp/main.cpp.o
/usr/share/arduino/hardware/tools/avr/bin/avr-g++ -c -g -Os -Wall -fno-exceptions -ffunction-sections -fdata-sections -mmcu=atmega328p -DF_CPU=16000000L -MMD -DUSB_VID=null -DUSB_PID=null -DARDUINO=105 -D__PROG_TYPES_COMPAT__ -I/usr/share/arduino/hardware/arduino/cores/arduino -I/usr/share/arduino/hardware/arduino/variants/standard /usr/share/arduino/hardware/arduino/cores/arduino/Tone.cpp -o /tmp/build4933543797518254688.tmp/Tone.cpp.o
/usr/share/arduino/hardware/tools/avr/bin/avr-g++ -c -g -Os -Wall -fno-exceptions -ffunction-sections -fdata-sections -mmcu=atmega328p -DF_CPU=16000000L -MMD -DUSB_VID=null -DUSB_PID=null -DARDUINO=105 -D__PROG_TYPES_COMPAT__ -I/usr/share/arduino/hardware/arduino/cores/arduino -I/usr/share/arduino/hardware/arduino/variants/standard /usr/share/arduino/hardware/arduino/cores/arduino/IPAddress.cpp -o /tmp/build4933543797518254688.tmp/IPAddress.cpp.o
/usr/share/arduino/hardware/tools/avr/bin/avr-g++ -c -g -Os -Wall -fno-exceptions -ffunction-sections -fdata-sections -mmcu=atmega328p -DF_CPU=16000000L -MMD -DUSB_VID=null -DUSB_PID=null -DARDUINO=105 -D__PROG_TYPES_COMPAT__ -I/usr/share/arduino/hardware/arduino/cores/arduino -I/usr/share/arduino/hardware/arduino/variants/standard /usr/share/arduino/hardware/arduino/cores/arduino/USBCore.cpp -o /tmp/build4933543797518254688.tmp/USBCore.cpp.o
/usr/share/arduino/hardware/tools/avr/bin/avr-g++ -c -g -Os -Wall -fno-exceptions -ffunction-sections -fdata-sections -mmcu=atmega328p -DF_CPU=16000000L -MMD -DUSB_VID=null -DUSB_PID=null -DARDUINO=105 -D__PROG_TYPES_COMPAT__ -I/usr/share/arduino/hardware/arduino/cores/arduino -I/usr/share/arduino/hardware/arduino/variants/standard /usr/share/arduino/hardware/arduino/cores/arduino/WString.cpp -o /tmp/build4933543797518254688.tmp/WString.cpp.o
/usr/share/arduino/hardware/tools/avr/bin/avr-ar rcs /tmp/build4933543797518254688.tmp/core.a /tmp/build4933543797518254688.tmp/wiring_analog.c.o
/usr/share/arduino/hardware/tools/avr/bin/avr-ar rcs /tmp/build4933543797518254688.tmp/core.a /tmp/build4933543797518254688.tmp/malloc.c.o
/usr/share/arduino/hardware/tools/avr/bin/avr-ar rcs /tmp/build4933543797518254688.tmp/core.a /tmp/build4933543797518254688.tmp/realloc.c.o
/usr/share/arduino/hardware/tools/avr/bin/avr-ar rcs /tmp/build4933543797518254688.tmp/core.a /tmp/build4933543797518254688.tmp/wiring_digital.c.o
/usr/share/arduino/hardware/tools/avr/bin/avr-ar rcs /tmp/build4933543797518254688.tmp/core.a /tmp/build4933543797518254688.tmp/wiring_pulse.c.o
/usr/share/arduino/hardware/tools/avr/bin/avr-ar rcs /tmp/build4933543797518254688.tmp/core.a /tmp/build4933543797518254688.tmp/wiring.c.o
/usr/share/arduino/hardware/tools/avr/bin/avr-ar rcs /tmp/build4933543797518254688.tmp/core.a /tmp/build4933543797518254688.tmp/wiring_shift.c.o
/usr/share/arduino/hardware/tools/avr/bin/avr-ar rcs /tmp/build4933543797518254688.tmp/core.a /tmp/build4933543797518254688.tmp/WInterrupts.c.o
/usr/share/arduino/hardware/tools/avr/bin/avr-ar rcs /tmp/build4933543797518254688.tmp/core.a /tmp/build4933543797518254688.tmp/Stream.cpp.o
/usr/share/arduino/hardware/tools/avr/bin/avr-ar rcs /tmp/build4933543797518254688.tmp/core.a /tmp/build4933543797518254688.tmp/HID.cpp.o
/usr/share/arduino/hardware/tools/avr/bin/avr-ar rcs /tmp/build4933543797518254688.tmp/core.a /tmp/build4933543797518254688.tmp/Print.cpp.o
/usr/share/arduino/hardware/tools/avr/bin/avr-ar rcs /tmp/build4933543797518254688.tmp/core.a /tmp/build4933543797518254688.tmp/WMath.cpp.o
/usr/share/arduino/hardware/tools/avr/bin/avr-ar rcs /tmp/build4933543797518254688.tmp/core.a /tmp/build4933543797518254688.tmp/CDC.cpp.o
/usr/share/arduino/hardware/tools/avr/bin/avr-ar rcs /tmp/build4933543797518254688.tmp/core.a /tmp/build4933543797518254688.tmp/new.cpp.o
/usr/share/arduino/hardware/tools/avr/bin/avr-ar rcs /tmp/build4933543797518254688.tmp/core.a /tmp/build4933543797518254688.tmp/HardwareSerial.cpp.o
/usr/share/arduino/hardware/tools/avr/bin/avr-ar rcs /tmp/build4933543797518254688.tmp/core.a /tmp/build4933543797518254688.tmp/main.cpp.o
/usr/share/arduino/hardware/tools/avr/bin/avr-ar rcs /tmp/build4933543797518254688.tmp/core.a /tmp/build4933543797518254688.tmp/Tone.cpp.o
/usr/share/arduino/hardware/tools/avr/bin/avr-ar rcs /tmp/build4933543797518254688.tmp/core.a /tmp/build4933543797518254688.tmp/IPAddress.cpp.o
/usr/share/arduino/hardware/tools/avr/bin/avr-ar rcs /tmp/build4933543797518254688.tmp/core.a /tmp/build4933543797518254688.tmp/USBCore.cpp.o
/usr/share/arduino/hardware/tools/avr/bin/avr-ar rcs /tmp/build4933543797518254688.tmp/core.a /tmp/build4933543797518254688.tmp/WString.cpp.o
/usr/share/arduino/hardware/tools/avr/bin/avr-gcc -Os -Wl,--gc-sections -mmcu=atmega328p -o /tmp/build4933543797518254688.tmp/Sweep.cpp.elf /tmp/build4933543797518254688.tmp/Sweep.cpp.o /tmp/build4933543797518254688.tmp/Servo/Servo.cpp.o /tmp/build4933543797518254688.tmp/core.a -L/tmp/build4933543797518254688.tmp -lm
/usr/share/arduino/hardware/tools/avr/bin/avr-objcopy -O ihex -j .eeprom --set-section-flags=.eeprom=alloc,load --no-change-warnings --change-section-lma .eeprom=0 /tmp/build4933543797518254688.tmp/Sweep.cpp.elf /tmp/build4933543797518254688.tmp/Sweep.cpp.eep
/usr/share/arduino/hardware/tools/avr/bin/avr-objcopy -O ihex -R .eeprom /tmp/build4933543797518254688.tmp/Sweep.cpp.elf /tmp/build4933543797518254688.tmp/Sweep.cpp.hex
Binary sketch size: 2,554 bytes (of a 32,256 byte maximum)
/usr/share/arduino/hardware/tools/avrdude -C/usr/share/arduino/hardware/tools/avrdude.conf -v -v -v -v -patmega328p -carduino -P/dev/ttyACM0 -b115200 -D -Uflash:w:/tmp/build4933543797518254688.tmp/Sweep.cpp.hex:i
avrdude: Version 6.0.1, compiled on Oct 21 2013 at 15:55:32
Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
Copyright (c) 2007-2009 Joerg Wunsch
System wide configuration file is "/usr/share/arduino/hardware/tools/avrdude.conf"
User configuration file is "/home/username/.avrduderc"
User configuration file does not exist or is not a regular file, skipping
Using Port : /dev/ttyACM0
Using Programmer : arduino
Overriding Baud Rate : 115200
avrdude: ser_open(): can't open device "/dev/ttyACM0": No such file or directory
ioctl("TIOCMGET"): Inappropriate ioctl for device
avrdude done. Thank you.
</code></pre>
<p><strong>Update 2:</strong> (tried again, this time i get "broken pipe". Led 13 blinks like crazy and my servo sounds different, no movement but continues sound)</p>
<pre><code>.
.
.
avrdude: avr_read(): skipping page 253: no interesting data
avrdude: avr_read(): skipping page 254: no interesting data
avrdude: avr_read(): skipping page 255: no interesting data
avrdude: verifying ...
avrdude: 2554 bytes of flash verified
avrdude: Send: Q [51] [20]
avrdude: Recv: . [14]
avrdude: Recv: . [10]
avrdude done. Thank you.
/usr/share/arduino/hardware/tools/avr/bin/avr-g++ -c -g -Os -Wall -fno-exceptions -ffunction-sections -fdata-sections -mmcu=atmega328p -DF_CPU=16000000L -MMD -DUSB_VID=null -DUSB_PID=null -DARDUINO=105 -D__PROG_TYPES_COMPAT__ -I/usr/share/arduino/hardware/arduino/cores/arduino -I/usr/share/arduino/hardware/arduino/variants/standard -I/usr/share/arduino/libraries/Servo /tmp/build4258280580047414287.tmp/Sweep.cpp -o /tmp/build4258280580047414287.tmp/Sweep.cpp.o
Using previously compiled: /tmp/build4258280580047414287.tmp/Servo/Servo.cpp.o
Using previously compiled: /tmp/build4258280580047414287.tmp/wiring_analog.c.o
Using previously compiled: /tmp/build4258280580047414287.tmp/malloc.c.o
Using previously compiled: /tmp/build4258280580047414287.tmp/realloc.c.o
Using previously compiled: /tmp/build4258280580047414287.tmp/wiring_digital.c.o
Using previously compiled: /tmp/build4258280580047414287.tmp/wiring_pulse.c.o
Using previously compiled: /tmp/build4258280580047414287.tmp/wiring.c.o
Using previously compiled: /tmp/build4258280580047414287.tmp/wiring_shift.c.o
Using previously compiled: /tmp/build4258280580047414287.tmp/WInterrupts.c.o
Using previously compiled: /tmp/build4258280580047414287.tmp/Stream.cpp.o
Using previously compiled: /tmp/build4258280580047414287.tmp/HID.cpp.o
Using previously compiled: /tmp/build4258280580047414287.tmp/Print.cpp.o
Using previously compiled: /tmp/build4258280580047414287.tmp/WMath.cpp.o
Using previously compiled: /tmp/build4258280580047414287.tmp/CDC.cpp.o
Using previously compiled: /tmp/build4258280580047414287.tmp/new.cpp.o
Using previously compiled: /tmp/build4258280580047414287.tmp/HardwareSerial.cpp.o
Using previously compiled: /tmp/build4258280580047414287.tmp/main.cpp.o
Using previously compiled: /tmp/build4258280580047414287.tmp/Tone.cpp.o
Using previously compiled: /tmp/build4258280580047414287.tmp/IPAddress.cpp.o
Using previously compiled: /tmp/build4258280580047414287.tmp/USBCore.cpp.o
Using previously compiled: /tmp/build4258280580047414287.tmp/WString.cpp.o
/usr/share/arduino/hardware/tools/avr/bin/avr-ar rcs /tmp/build4258280580047414287.tmp/core.a /tmp/build4258280580047414287.tmp/wiring_analog.c.o
/usr/share/arduino/hardware/tools/avr/bin/avr-ar rcs /tmp/build4258280580047414287.tmp/core.a /tmp/build4258280580047414287.tmp/malloc.c.o
/usr/share/arduino/hardware/tools/avr/bin/avr-ar rcs /tmp/build4258280580047414287.tmp/core.a /tmp/build4258280580047414287.tmp/realloc.c.o
/usr/share/arduino/hardware/tools/avr/bin/avr-ar rcs /tmp/build4258280580047414287.tmp/core.a /tmp/build4258280580047414287.tmp/wiring_digital.c.o
/usr/share/arduino/hardware/tools/avr/bin/avr-ar rcs /tmp/build4258280580047414287.tmp/core.a /tmp/build4258280580047414287.tmp/wiring_pulse.c.o
/usr/share/arduino/hardware/tools/avr/bin/avr-ar rcs /tmp/build4258280580047414287.tmp/core.a /tmp/build4258280580047414287.tmp/wiring.c.o
/usr/share/arduino/hardware/tools/avr/bin/avr-ar rcs /tmp/build4258280580047414287.tmp/core.a /tmp/build4258280580047414287.tmp/wiring_shift.c.o
/usr/share/arduino/hardware/tools/avr/bin/avr-ar rcs /tmp/build4258280580047414287.tmp/core.a /tmp/build4258280580047414287.tmp/WInterrupts.c.o
/usr/share/arduino/hardware/tools/avr/bin/avr-ar rcs /tmp/build4258280580047414287.tmp/core.a /tmp/build4258280580047414287.tmp/Stream.cpp.o
/usr/share/arduino/hardware/tools/avr/bin/avr-ar rcs /tmp/build4258280580047414287.tmp/core.a /tmp/build4258280580047414287.tmp/HID.cpp.o
/usr/share/arduino/hardware/tools/avr/bin/avr-ar rcs /tmp/build4258280580047414287.tmp/core.a /tmp/build4258280580047414287.tmp/Print.cpp.o
/usr/share/arduino/hardware/tools/avr/bin/avr-ar rcs /tmp/build4258280580047414287.tmp/core.a /tmp/build4258280580047414287.tmp/WMath.cpp.o
/usr/share/arduino/hardware/tools/avr/bin/avr-ar rcs /tmp/build4258280580047414287.tmp/core.a /tmp/build4258280580047414287.tmp/CDC.cpp.o
/usr/share/arduino/hardware/tools/avr/bin/avr-ar rcs /tmp/build4258280580047414287.tmp/core.a /tmp/build4258280580047414287.tmp/new.cpp.o
/usr/share/arduino/hardware/tools/avr/bin/avr-ar rcs /tmp/build4258280580047414287.tmp/core.a /tmp/build4258280580047414287.tmp/HardwareSerial.cpp.o
/usr/share/arduino/hardware/tools/avr/bin/avr-ar rcs /tmp/build4258280580047414287.tmp/core.a /tmp/build4258280580047414287.tmp/main.cpp.o
/usr/share/arduino/hardware/tools/avr/bin/avr-ar rcs /tmp/build4258280580047414287.tmp/core.a /tmp/build4258280580047414287.tmp/Tone.cpp.o
/usr/share/arduino/hardware/tools/avr/bin/avr-ar rcs /tmp/build4258280580047414287.tmp/core.a /tmp/build4258280580047414287.tmp/IPAddress.cpp.o
/usr/share/arduino/hardware/tools/avr/bin/avr-ar rcs /tmp/build4258280580047414287.tmp/core.a /tmp/build4258280580047414287.tmp/USBCore.cpp.o
/usr/share/arduino/hardware/tools/avr/bin/avr-ar rcs /tmp/build4258280580047414287.tmp/core.a /tmp/build4258280580047414287.tmp/WString.cpp.o
/usr/share/arduino/hardware/tools/avr/bin/avr-gcc -Os -Wl,--gc-sections -mmcu=atmega328p -o /tmp/build4258280580047414287.tmp/Sweep.cpp.elf /tmp/build4258280580047414287.tmp/Sweep.cpp.o /tmp/build4258280580047414287.tmp/Servo/Servo.cpp.o /tmp/build4258280580047414287.tmp/core.a -L/tmp/build4258280580047414287.tmp -lm
/usr/share/arduino/hardware/tools/avr/bin/avr-objcopy -O ihex -j .eeprom --set-section-flags=.eeprom=alloc,load --no-change-warnings --change-section-lma .eeprom=0 /tmp/build4258280580047414287.tmp/Sweep.cpp.elf /tmp/build4258280580047414287.tmp/Sweep.cpp.eep
/usr/share/arduino/hardware/tools/avr/bin/avr-objcopy -O ihex -R .eeprom /tmp/build4258280580047414287.tmp/Sweep.cpp.elf /tmp/build4258280580047414287.tmp/Sweep.cpp.hex
Binary sketch size: 2,554 bytes (of a 32,256 byte maximum)
/usr/share/arduino/hardware/tools/avrdude -C/usr/share/arduino/hardware/tools/avrdude.conf -v -v -v -v -patmega328p -carduino -P/dev/ttyACM0 -b115200 -D -Uflash:w:/tmp/build4258280580047414287.tmp/Sweep.cpp.hex:i
avrdude: Version 6.0.1, compiled on Oct 21 2013 at 15:55:32
Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
Copyright (c) 2007-2009 Joerg Wunsch
System wide configuration file is "/usr/share/arduino/hardware/tools/avrdude.conf"
User configuration file is "/home/username/.avrduderc"
User configuration file does not exist or is not a regular file, skipping
Using Port : /dev/ttyACM0
Using Programmer : arduino
Overriding Baud Rate : 115200
ioctl("TIOCMSET"): Broken pipe
ioctl("TIOCMGET"): Input/output error
</code></pre>
| <p>Please use the last IDE version released here: arduino.cc/en/Main/Software The version 1.6.1 has many improvements about serial devices detection and sketches upload. It will solve your issues about older Arduino UNO version and Arduino Yun. </p>
|
9193 | |arduino-uno|c++|wifi| | Arduino Uno with CC3000 WiFi Shield cannot be initialized | 2015-03-10T12:08:44.220 | <p>I am working on an Arduino Uno and CC3000 WiFi shield. I interfaced it over my Arduino and added the SparkFun library <code>SFE_CC3000_Library</code>. Then I opened the TestBoard example, but it hangs on setup in the first command <code>wifi.init()</code>.</p>
<p>How can I solve this problem, and how can I enable debug mode?</p>
<p>Here's the code</p>
<pre><code>#include <SPI.h>
#include <SFE_CC3000.h>
#include <utility/netapp.h>
#define DEBUG 1
// Pins
#define CC3000_INT 2 // Needs to be an interrupt pin (D2/D3)
#define CC3000_EN 7 // Can be any digital pin
#define CC3000_CS 10 // Preferred is pin 10 on Uno
// Constants
#define FW_VER_LEN 2 // Length of firmware version in bytes
#define MAC_ADDR_LEN 6 // Length of MAC address in bytes
// Global Variables
SFE_CC3000 wifi = SFE_CC3000(CC3000_INT, CC3000_EN, CC3000_CS);
void setup() {
int i;
unsigned char fw_ver[FW_VER_LEN];
unsigned char mac_addr[MAC_ADDR_LEN];
// Initialize Serial port
Serial.begin(115200);
Serial.println();
Serial.println("----------------------------");
Serial.println("SparkFun CC3000 - Board Test");
Serial.println("----------------------------");
// Initialize CC3000 (configure SPI communications)
if ( wifi.init() ) {
digitalWrite(13, HIGH);
Serial.println("CC3000 initialization complete");
} else {
Serial.println("Something went wrong during CC3000 init!");
}
// Read and display CC3000 firmware version
if ( wifi.getFirmwareVersion(fw_ver) ) {
Serial.print("Firmware version: ");
Serial.print(fw_ver[0], DEC);
Serial.print(".");
Serial.print(fw_ver[1], DEC);
Serial.println();
} else {
Serial.println("Could not read firmware version from CC3000");
}
// Read and display CC3000 MAC address
if ( wifi.getMacAddress(mac_addr) ) {
Serial.print("MAC address: ");
for ( i = 0; i < MAC_ADDR_LEN; i++ ) {
if ( mac_addr[i] < 0x10 ) {
Serial.print("0");
}
Serial.print(mac_addr[i], HEX);
if ( i < MAC_ADDR_LEN - 1 ) {
Serial.print(":");
}
}
Serial.println();
} else {
Serial.println("Could not read MAC address from CC3000");
}
// Done!
Serial.println("Finished board test");
}
void loop() {
// Do nothing
delay(1000);
Serial.println("Loop_Problem");
}
</code></pre>
| <p>Solved it, the problem was because the SparkFun library was not working with my shield. I replaced it using the <code>Adafruit_CC3000_Library</code> and now it works fine.</p>
|
9205 | |arduino-uno|power|usb| | Powering USB device from arduino uno? | 2015-03-11T12:16:20.317 | <p>I'm wanting to power a USB device from an Arduino Uno. Forgetting about the two data pins, it just requires power. Using a power meter, I can detect the 5v pin at about 4.95 volts, however I don't have access to any resistors at the moment so cannot test the amperage because it just shorts.</p>
<p>The USB device I want to power requires ~300mA (can't remember specifically). First of all, does the Arduino get 100mA or 500mA when getting power from the USB? Is this changeable depending on the setting on the USB Host (High 500mA, or Low 100mA)? </p>
<p>Secondly, how much would actually be usable? I assume the Arduino itself would require some of that current? Even more if a program where running on it at the same time? (I have no idea how computers utilize power) I would like to just hook up my usb device to ground and 5V with whatever resistors (and any other electrical components) in between to bring it down from 500mA to the required ~300mA.</p>
| <p>The Arduino receives 500mA max from USB power. That is per the USB specification, and the Arduino has a 500mA resettable fuse on the USB power to protect your computer's USB port from 'accidents'.</p>
<p>As to the question of whether it is configurable between 500mA/100mA, generally no it's not. I believe that part of the USB negotiation that occurs when the Arduino connects to your PC is that the Arduino describes itself to the computer, and it reports that it is a 500mA device. Bottom line is, you won't need to do anything special in this regard.</p>
<p>Now, how much of the power is needed for the Arduino, and how much is left over - well that depends on what else the Arduino is doing and what else it's powering (LEDs, etc.). If the Arduino is not doing much else, than 200mA should be plenty of headroom for it.</p>
<p>If you power the Arduino through the PWR Jack (or the Vin), then the voltage should be a minimum of 7V. That is because it is feeding into a 5v regulator, which has some voltage drop, so it needs about 7V to be able to consistently supply 5V output. If you power the Arduino manually (through the 5V pin), you want to give it 5V. Anything less than 5V would be considered overclocking. (The ATMEGA328P needs 5V to operate at 16mHz, but can run at lower voltages when clocked at lower speeds.)</p>
<p>Also, keep in mind that the USB port on the Arduino is a USB 'client', not a USB host or USB OTG. Therefore, the port can not be used to supply outbound power. You can power your extra device from the Arduino's 5V and GND pins.</p>
|
9207 | |arduino-uno|battery|temperature-sensor| | which is the most efficient way to save power with battery using Arduino UNO? | 2015-03-11T15:41:24.920 | <p>I am working with a ArduinoUNO - 2100 mA battery, and a solar Charger shield. I use a temperature reader that sends info <strong>every half hour with GPS-GSM shield</strong> called LONET (<a href="http://www.seeedstudio.com/wiki/LoNet_-_GSM/GPRS/GPS_Breakout" rel="nofollow">http://www.seeedstudio.com/wiki/LoNet_-_GSM/GPRS/GPS_Breakout</a> for more info).</p>
<p>I want to save all the energy i can, i am trying to put Arduino UNO and LONET on Sleep mode.</p>
<p>LONE has its own mode via “AT+CSCLK=1”. </p>
<p>But for Arduino UNO i haven seen a library called Narcoleptic (<a href="https://code.google.com/p/narcoleptic/" rel="nofollow">https://code.google.com/p/narcoleptic/</a> for more info) wich can solve the problem.</p>
<p>My question is:</p>
<p>Is there any other method that can help me to save Battery with Arduino uno? is it a good approach to use Narcoleptic or there is another method to do it?</p>
<p>Thanks for your time/help and sorry for my English.</p>
<p>Any feedback could be welcome.</p>
| <p>There is an even greater article on this topic: <a href="http://www.gammon.com.au/power" rel="nofollow noreferrer">http://www.gammon.com.au/power</a></p>
<p>It shows how to reduce your power usage for the Uno from about 50mA to 350nA (0.000350mA) - at this point, you need to factor in the natural drain of batteries.</p>
<p>Also, I have had good success with a project that was activated by a pushbutton, by using a latch - the push button turned the power on; once the power is on, it latched. Then the Arduino can switch itself off, using one of it's pins. As far as I can tell from a simulator, there is no leakage (while it is off, to within the accuracy of the simulator, assuming a perfectly spherical transistor in a vacuum ;) ). </p>
<p>Just in case anyone is interested, my latch circuit can be seen at: <a href="https://i.stack.imgur.com/Uf9sX.png" rel="nofollow noreferrer">https://i.stack.imgur.com/Uf9sX.png</a> - the two resistors and the switch at the bottom represent the Arduino - +5V coming in the top, GND at the bottom, and one of the pin to switch it off is the switch - this pin should be INPUT to keep the power on; when you are ready to switch of, set it to output -> high. You should get switched off immediately. The switch at the top will switch it on. In the startup part of your sketch, set the pin to INPUT first.</p>
|
9219 | |sensors|map| | Why is the constrain function used after the map function? | 2015-03-12T09:55:32.013 | <p>I am reading some sample code and they use this method of mapping data from IR sensors:</p>
<pre><code> sensor1 = analogRead(0);
adj_1 = map(sensor1, s1_min, s1_max, 0, 255);
adj_1 = constrain(adj_1, 0, 255);
</code></pre>
<p>What is the point of using <code>constrain</code> here if <code>adj_1</code> is already getting a value 0-255 from the <code>map</code> function?</p>
| <p>One caveat would be when mapping an input that ranges from 0 to 1023, since the Arduino is incapable of reading outside of this range there would be no need to constrain. You can check this by running through each iteration from 0 to 1023 and outputting the corresponding mapped value:</p>
<pre><code>for (int i = 0; i < 1024; i++){
Serial.print(i);
Serial.print(",");
Serial.println(map(i, 0, 1023, 0, 255));
}
</code></pre>
<p>Certainly, if your sensor reading offers a range smaller than 0 to 1023, then the constrain() function is definitely required, as per LoganBlade's example. Otherwise, it is not needed, but may still fall into the realm of best practice.</p>
<p>The only hiccup to this logic would be if you are mapping to decimal values (which doesn't make much sense since the function will return a long type anyway), in which case the Arduino's internal typecasting will round-down your lowest value mapping. Example:</p>
<pre><code>map(0, 0, 1023, 8.9, 61.9));
>> 0 becomes 8
map(1023, 0, 1023, 8.9, 61.9));
>> 1023 becomes 61
</code></pre>
<p>Again, for the sake of best practice and the potential time wasted trying to find a mapping bug, using constrain() is better than skipping it.</p>
|
9230 | |arduino-uno|arduino-mega|atmega328| | Difficult between atmega328 & atmega2560 when coding & compiling in a pure c | 2015-03-12T18:23:47.323 | <p>I have an arduino uno with atmega328p controller.</p>
<p>I found the code to deal with some specific uart protocol, named mdb: <a href="https://github.com/Bouni/MateDealer/tree/master/arduino" rel="nofollow">https://github.com/Bouni/MateDealer/tree/master/arduino</a></p>
<p>But it's compiled just for atmega2560 controller: <a href="https://github.com/Bouni/MateDealer/blob/master/arduino/makefile#L42" rel="nofollow">https://github.com/Bouni/MateDealer/blob/master/arduino/makefile#L42</a></p>
<p>If I replace it by <code>atmega328p</code> or <code>atmega328</code>, I get the error:</p>
<pre><code>asiniy@misha:~/projects/MateDealer/arduino$ make all
-------- begin --------
avr-gcc (GCC) 4.8.2
Copyright (C) 2013 Free Software Foundation, Inc.
This is free software; see the source for copying conditions. There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
Compiling: main.c
avr-gcc -c -mmcu=atmega328 -I. -gdwarf-2 -Os -funsigned-char -funsigned-bitfields -fpack-struct -fshort-enums -Wall -Wstrict-prototypes -Wa,-adhlns=main.lst -std=gnu99 -DF_OSC=16000000 -MD -MP -MF .dep/main.o.d main.c -o main.o
Compiling: usart.c
avr-gcc -c -mmcu=atmega328 -I. -gdwarf-2 -Os -funsigned-char -funsigned-bitfields -fpack-struct -fshort-enums -Wall -Wstrict-prototypes -Wa,-adhlns=usart.lst -std=gnu99 -DF_OSC=16000000 -MD -MP -MF .dep/usart.o.d usart.c -o usart.o
usart.c:25:40: error: ‘UBRR1H’ undeclared here (not in a function)
{ { { {}, 0, 0 }, { {}, 0, 0 } }, &UBRR1H, &UBRR1L, &UCSR1B, &UCSR1C },
^
usart.c:25:49: error: ‘UBRR1L’ undeclared here (not in a function)
{ { { {}, 0, 0 }, { {}, 0, 0 } }, &UBRR1H, &UBRR1L, &UCSR1B, &UCSR1C },
^
usart.c:25:58: error: ‘UCSR1B’ undeclared here (not in a function)
{ { { {}, 0, 0 }, { {}, 0, 0 } }, &UBRR1H, &UBRR1L, &UCSR1B, &UCSR1C },
^
usart.c:25:67: error: ‘UCSR1C’ undeclared here (not in a function)
{ { { {}, 0, 0 }, { {}, 0, 0 } }, &UBRR1H, &UBRR1L, &UCSR1B, &UCSR1C },
^
In file included from usart.c:14:0:
usart.c: In function ‘USART0_RX_vect’:
usart.c:185:5: warning: ‘USART0_RX_vect’ appears to be a misspelled signal handler [enabled by default]
ISR(USART0_RX_vect){
^
usart.c: In function ‘USART1_RX_vect’:
usart.c:197:5: warning: ‘USART1_RX_vect’ appears to be a misspelled signal handler [enabled by default]
ISR(USART1_RX_vect){
^
usart.c:203:12: error: ‘UDR1’ undeclared (first use in this function)
data = UDR1;
^
usart.c:203:12: note: each undeclared identifier is reported only once for each function it appears in
In file included from usart.c:14:0:
usart.c: In function ‘USART0_UDRE_vect’:
usart.c:233:5: warning: ‘USART0_UDRE_vect’ appears to be a misspelled signal handler [enabled by default]
ISR(USART0_UDRE_vect){
^
usart.c: In function ‘USART1_UDRE_vect’:
usart.c:253:5: warning: ‘USART1_UDRE_vect’ appears to be a misspelled signal handler [enabled by default]
ISR(USART1_UDRE_vect){
^
usart.c:261:31: error: ‘TXB81’ undeclared (first use in this function)
UCSR1B |= (1<<TXB81);
^
usart.c:266:9: error: ‘UDR1’ undeclared (first use in this function)
UDR1 = data;
^
usart.c:269:20: error: ‘UDRIE1’ undeclared (first use in this function)
UCSR1B &= ~(1<<UDRIE1);
^
make: *** [usart.o] Error 1
</code></pre>
<p>I've tried to play with compilers (default is gnu99) and so on, but with no success. Why I have this trouble? How can I compile this code for upload it to arduino?</p>
| <p>I'm the author of the MateDealer project and I never had the intention to port it to other boards than the Arduino Mega2560! </p>
<p>Ignacio Vazquez-Abrams is absolutely right, the Arduino Mega2560 is the only board with more than 1 serial port (Yes there is the Due and the Leonardo, but those would require major changes to the code).</p>
<p>The fastest way to get the code running is by using a Mega2560, but be warned, the code might be bugy as hell ;-)</p>
|
9236 | |c++|data-type| | Can I have help interperting this code? char variable somehow storing big numbers | 2015-03-12T21:06:00.240 | <p>I have this GSM module I got for my arduino project and I am trying to access the call feature, but the function makes no sense.</p>
<pre><code> boolean Adafruit_FONA::callPhone(char *number) {
char sendbuff[35] = "ATD";
strncpy(sendbuff+3, number, min(30, strlen(number)));
uint8_t x = strlen(sendbuff);
sendbuff[x] = ';';
sendbuff[x+1] = 0;
//Serial.println(sendbuff);
return sendCheckReply(sendbuff, "OK");
}
</code></pre>
<p>This is the function however how is char being used to display a phone number in the parameter? </p>
| <p>Keeping it simple:</p>
<p><code>char *number;</code> a variable pointing to a character (or string of them).<br>
<code>char sendbuff[35];</code> 35 characters in a row, making a string.<br>
The first 3 chars at locatiion sendbuff are initialised to "A", "T", & "D", then the string at "number" is copied to it (to a maximum of 30 characters, by taking the lesser of the length of "number" or 30. This is important to avoid over-running the space allocated.<br>
This string of characters gets sent out; & a check is made for an "O" & a "K"</p>
<p>If you don't 'get' pointers, you need to look it up, as it's pretty central stuff.</p>
|
9242 | |serial|arduino-mega|sensors|interrupt| | What happens if an interrupt is triggered while sending data via serial? | 2015-03-13T00:59:50.187 | <p>I would like to use an inertial sensor to measure acceleration and send the results to an Android app using a serial communication with a <strong>bluetooth Mate Gold</strong> module. The sensor provides a data ready interrupt which notifies <strong>Arduino-Mega</strong> that a new value is stored in a register of the module. The output data rate can be modified during the configuration of the sensor.
I want the information to be sent at a 10 Hz rate to the bluetooth module.</p>
<p>Is an interrupt at 400Hz capable of compromising the integrity of a 50 bytes long message sent at 10 Hz with a baudrate of 9600?
If yes, which approach would you recommend to correctly send the data?</p>
<p><strong>Edit</strong>:
I'm using the following formula to compute the amount of time required to send N chars.</p>
<pre><code>bytes x bits_per_character / bits_per_second
N x (8+2) / 9600 = N/960 secs
</code></pre>
<p>For N = 52:</p>
<pre><code>52/960 = 0.054 secs = 54 ms
</code></pre>
<p>So theoretically, I can send a 54 char-long message at 18Hz with a baudrate of 9600. </p>
<p><strong>Edit2</strong>
I can use the hardware serial or the Software Serial interface.</p>
| <p>You want to send a 50 byte (or 52 byte?) sequence every 100 ms (10 Hz).</p>
<p>For hardware serial, that will go into a buffer which is emptied via serial interrupts; it should be emptied well before the next 100 ms tic (as you have calculated).</p>
<p>You will get about 40 sensor interrupts during that 100 ms. With hardware serial, that need not be a problem - <strong>so long as you don't send bytes from within a sensor interrupt</strong>. If your sensor interrupt just accumulates results and the main loop (non-interrupt) uses those results to periodically send the 50 byte message, you should be good.</p>
<p>Suppose you were averaging each of the sensor readings. In the sensor interrupt you might add 1 to the count and add the reading to a sum value. In the main loop, test if it has it has been 100 msec since the last send, and if so turn off interrupts, divide the sum by the count and store that average in a new variable, zero the sum and count, turn on interrupts. Then use the computed average to format and send the 50 byte package.</p>
<p>That's just an example. The main thing is to make the sensor interrupt quick and simple; and to format and send the packet in the main loop (inhibiting interrupts temporarily while fetching and clearing the variables which get updated during the sensor interrupt).</p>
<p>Be sure to use "volatile" for the variables used by both the sensor interrupt and the main loop.</p>
<p>The serial should take care of itself if you use hardware serial, and might even be OK for software serial. In the latter case, a sensor interrupt in the middle of sending the bits of a single character/byte would mess up the bit timing, but software serial should inhibit interrupts during that time - so your sensor interrupt might be delayed up to a millisecond.</p>
|
9244 | |arduino-uno|i2c|attiny| | I²C between ATTiny85 (8MHz) and Arduino Uno | 2015-03-13T05:40:31.453 | <p>I keep receiving the following error in myATTiny85-Slave code below:</p>
<blockquote>
<p>sketch_mar12a.ino: In function 'void setup()':</p>
<p>sketch_mar12a:19: error: 'class USI_TWI_S' has no member named 'onRequest'</p>
</blockquote>
<p>I have downloaded <strong><a href="https://github.com/rambo/TinyWire/tree/master/TinyWireS" rel="nofollow noreferrer">TinyWireS</a></strong> and <em>TinyWireS.h</em> clearly has a public function <strong>onRequest</strong>. I opened the .ZIP file (downloaded from <a href="https://github.com/rambo/TinyWire" rel="nofollow noreferrer">https://github.com/rambo/TinyWire</a>) and drag-dropped TinyWireS folder into the Arduino libraries folder. This is how I install ALL libraries.</p>
<p><strong>I am using Arduino 1.0.6</strong></p>
<p>What am I doing wrong?</p>
<h2>ATTiny85-Slave Code:</h2>
<pre><code>#include "TinyWireS.h" // wrapper class for I2C slave routines
#define I2C_SLAVE_ADDR 0x26 // i2c slave address (38)
byte t=10;
void setup()
{
TinyWireS.begin(I2C_SLAVE_ADDR); // init I2C Slave mode
TinyWireS.onRequest(requestEvent);
}
void loop()
{
}
void requestEvent()
{
TinyWireS.send(t);
}
</code></pre>
<h2>Arduino Uno-Master Code:</h2>
<pre><code> #include <Wire.h>
#define I2C_SLAVE_ADDR 0x26 // i2c slave address (38)
void setup()
{
Wire.begin();
Serial.begin(9600);
}
void loop()
{
byte num;
// read 1 byte, from address 0x26
Wire.requestFrom(I2C_SLAVE_ADDR, 1);
while(Wire.available()) {
num = Wire.read();
}
Serial.print("num = ");
Serial.println(num,DEC);
}
</code></pre>
| <p>I was able to compile your code "ATTiny85-Slave Code" without problems.</p>
<p>You can try to extract the contents of the ZIP archive (i.e. the library) directly to the directory where your sketch is stored. <code>#include "TinyWireS.h"</code> should then pick up that version.</p>
<p>You should also switch on verbose output for the compilation to have a look at the directory in which the code is compiled. Here you would find (at least in my older Arduino IDE version) copies of the included files. (<code>/tmp/build...</code> on Linux systems.) You can then make sure the proper version of the files is used. </p>
<p>You can also search your drives for other copies of <code>TinyWireS.h</code>.</p>
|
9287 | |arduino-uno|servo| | Stop servo when enter 0 | 2015-03-13T16:40:30.567 | <p>I am trying to stop servo motor from rotating when I enter 0 in serial. The code is below. Can someone please help?</p>
<pre class="lang-cpp prettyprint-override"><code>#include <Servo.h>
Servo myservo; // create servo object to control a servo
// twelve servo objects can be created on most boards
int state;
int pos = 0; // variable to store the servo position
void setup()
{
myservo.attach(9); // attaches the servo on pin 9 to the servo object
Serial.begin (9600);
}
void loop()
{
if (Serial.available () > 0)
{
state = Serial.read ();
if (state == '1')
{
for (pos = 0; pos <= 180; pos += 1)
{
myservo.write(pos); // tell servo to go to position in variable 'pos'
delay(15);
}
for (pos = 180; pos >= 0; pos -= 1)
{
myservo.write(pos); // tell servo to go to position in variable 'pos'
delay(15); // waits 15ms for the servo to reach the position
}
if (Serial.available () > 0)
{
state = Serial.read ();
if (state == '0')
{
myservo.write ('90');
delay (300);
}
}
}
}
}
</code></pre>
| <p>From the code you posted it looks like you have the right idea but you've nested the 'IF' statements causing the check for '0' to only happen if you send two bytes and it will only go to 90deg when you send '10'. The loop section should look more like:</p>
<pre><code>if(Serial.available()){
state = Serial.read();
if(state == '1'){
Make motor move;
}else if(state == '0'){
Make motor stop;
}//end of elseif
}//end of if
</code></pre>
|
9296 | |programming|c++|lcd|class| | Use object of other class within class | 2015-03-13T21:50:33.323 | <p>I am writing a class for a project which will take care of handling any LCD updates for my project. The way I want to handle this is to initialize the LCD object in my main file, and then pass the LCD object on to my own class when initializing it.
The LCD object should be declared a private object in my class so several member functions can access it.</p>
<p>The problem is I can't find how to initialize the object correctly in the .h file.
Below is what I currently have, but when I try to build it, I get:</p>
<pre><code>LCDController.h:_Clcd1' should be initialized
LCDController.h:_Clcd2' should be initialized
</code></pre>
<p>main .ino file:</p>
<pre><code>void setup()
{
//LiquidCrystal lcd(RS,RW,Enable1,Enable2, data3,data2,data1,data0);
LiquidCrystal lcd(12, 11, 7, 6, 5, 4); //declare two LCD's
LiquidCrystal lcd2(12, 10, 7, 6, 5, 4); // Ths is the second
LCDController.init(lcd, lcd2);
}
</code></pre>
<p>LCDController.h file:</p>
<pre><code>// LCDController.h
#ifndef _LCDCONTROLLER_h
#define _LCDCONTROLLER_h
#if defined(ARDUINO) && ARDUINO >= 100
#include "Arduino.h"
#else
#include "WProgram.h"
#endif
#include <LiquidCrystal.h>
class LCDControllerClass
{
protected:
public:
void init(LiquidCrystal& Clcd1, LiquidCrystal& Clcd2);
private:
void _UpdateLCD(int iLine, int iPosition, String cText);
LiquidCrystal& _Clcd1;
LiquidCrystal& _Clcd2;
};
extern LCDControllerClass LCDController;
#endif
</code></pre>
<p>LCDController.cpp file:</p>
<pre><code>#include "LCDController.h"
#include <LiquidCrystal.h>
void LCDControllerClass::init(LiquidCrystal& Clcd1, LiquidCrystal& Clcd2)
{
_Clcd1 = Clcd1;
_Clcd1.begin(40, 2);
_Clcd1.clear();
_Clcd2 = Clcd2;
_Clcd2.begin(40, 2);
_Clcd2.clear();
}
</code></pre>
| <p>In C++, a class that holds reference members (in your sample, <code>LiquidCrystal& _Clcd1;</code> and <code>LiquidCrystal& _Clcd2;</code>) must ensure these references are initialized at construction time, not later.</p>
<p>This means your <code>void init(LiquidCrystal& Clcd1, LiquidCrystal& Clcd2);</code> method is not the right way to initialize <code>_Clcd1</code> and <code>_Clcd2</code> because it will be called <strong>after construction time</strong>.</p>
<p>You have 2 ways to solve this issue,t hat I will detail further below.</p>
<p><strong>HOWEVER</strong>, before we discuss the solutions, you must be aware that your sample code has <strong>a huge defect in <code>setup()</code> method code</strong>!</p>
<pre><code>void setup()
{
//LiquidCrystal lcd(RS,RW,Enable1,Enable2, data3,data2,data1,data0);
LiquidCrystal lcd(12, 11, 7, 6, 5, 4); //declare two LCD's
LiquidCrystal lcd2(12, 10, 7, 6, 5, 4); // Ths is the second
LCDController.init(lcd, lcd2);
}
</code></pre>
<p>Here, you create <code>lcd</code> and <code>lcd2</code> in your <code>setup</code> method, but their life ends at the end of <code>setup()</code>, because they have been allocated <strong>on the stack</strong>. Using these outside <code>setup()</code> will most likely cause your program to crash as soon as your <code>loop()</code> tries to access <code>lcd</code> or <code>lcd2</code>, indirectly through <code>LCDController</code> method calls.</p>
<p>To remove this defect, you must declare these variables outside <code>setup</code>:</p>
<pre><code>//LiquidCrystal lcd(RS,RW,Enable1,Enable2, data3,data2,data1,data0);
LiquidCrystal lcd(12, 11, 7, 6, 5, 4); //declare two LCD's
LiquidCrystal lcd2(12, 10, 7, 6, 5, 4); // Ths is the second
void setup()
{
LCDController.init(lcd, lcd2);
}
</code></pre>
<p>Now you can use them anywhere in your program, you are sure they are present and "alive".</p>
<p>Now we can go to the solutions of the original compilation problem.</p>
<h1>1. Initialize references at construction by adding a constructor</h1>
<pre><code>class LCDControllerClass
{
public:
LCDControllerClass(LiquidCrystal& Clcd1, LiquidCrystal& Clcd2)
: _Clcd1(Clcd1), _Clcd2(Clcd2) {}
...
};
</code></pre>
<p>You can still keep an <code>void init()</code> method to complete the initialization if you don't want it to occur right at construction time, or you can fully integrate the current <code>init()</code> content into the constructor and re,voe <code>init()</code> altogether:</p>
<pre><code>class LCDControllerClass
{
public:
LCDControllerClass(LiquidCrystal& Clcd1, LiquidCrystal& Clcd2)
: _Clcd1(Clcd1), _Clcd2(Clcd2)
{
_Clcd1.begin(40, 2);
_Clcd1.clear();
_Clcd2.begin(40, 2);
_Clcd2.clear();
}
...
};
</code></pre>
<p>In anycase, you will have to change the way you instantiate your <code>LCDControllerClass LCDController</code> which you did not show in your sample code, that would be something like this:</p>
<pre><code>LiquidCrystal lcd(...);
LiquidCrystal lcd2(...);
LCDControllerClass LCDController(lcd, lcd2);
</code></pre>
<p>That obviously requires that you can instantitate <code>lcd</code> and <code>lcd2</code> <strong>before</strong> creating <code>LCDController</code>. If that is not possible for you, then you'll have to use the second way.</p>
<h1>2. Replace references with pointers</h1>
<p>As mentioned before, in a class reference members MUST be initialized at construction time (moreover, they cannot be changed afterwards, to point somewhere else). This is not the case for pointers however:</p>
<pre><code>class LCDControllerClass
{
public:
void init(LiquidCrystal* Clcd1, LiquidCrystal* Clcd2);
private:
void _UpdateLCD(int iLine, int iPosition, String cText);
LiquidCrystal* _Clcd1;
LiquidCrystal* _Clcd2;
};
void LCDControllerClass::init(LiquidCrystal* Clcd1, LiquidCrystal* Clcd2)
{
_Clcd1 = Clcd1;
_Clcd1->begin(40, 2);
_Clcd1->clear();
_Clcd2 = Clcd2;
_Clcd2->begin(40, 2);
_Clcd2->clear();
}
</code></pre>
<p>Note that now, you need to use the arrow notation <code>-></code> to access <code>_Clcd1</code> and <code>_Clcd2</code> members (dot notation cannot work for pointers).</p>
<p>The rest of the code should be slightly modified to reflect this change:</p>
<pre><code>//LiquidCrystal lcd(RS,RW,Enable1,Enable2, data3,data2,data1,data0);
LiquidCrystal lcd(12, 11, 7, 6, 5, 4); //declare two LCD's
LiquidCrystal lcd2(12, 10, 7, 6, 5, 4); // Ths is the second
void setup()
{
LCDController.init(&lcd, &lcd2);
}
</code></pre>
<p>Note that we now have to pass <strong>the address</strong> of <code>lcd</code> and <code>lcd2</code> to <code>init()</code>, by using <code>&</code> before their names.</p>
|
9302 | |usb|ftdi| | Regarding the USB port, what is the difference between Uno/Mega and the older boards? | 2015-03-14T08:09:15.340 | <p>I would like to know what the exact difference is between the Uno and Mega boards and the older boards (Duemilanove, Diecimila, etc.). Why do I need to install a FTDI driver for the older boards, and not for the Uno/Mega boards? I was in a class the other day, using the Nano, and the lecturer recommended the FTDI drivers. <strike>The Nano is a newer type board, so why does that require a driver?</strike> I've just discovered that the Nano is old tech from 2008, after reading <a href="https://arduino.stackexchange.com/questions/4480/are-there-any-reasons-to-pick-nano-over-micro/4489#4489">Are there any reasons to pick Nano over Micro?</a></p>
<p>What is it about the Uno and Mega boards that don't require the FTDI to be separately installed?</p>
<p>I see that the <a href="http://www.arduino.cc/en/Guide/MacOSX" rel="nofollow noreferrer">Getting Started w/ Arduino on Mac OS X</a> page states that the older boards use the FTDI chip. Does that imply that the Uno/Mega boards do not? If they do not, then what do they use?</p>
<p>I have a vague notion that some USB sticks, keyboards, mouse and other various USB devices may contain a driver within the circuitry/firmware(?) of the device, which when connected to a PC for the first time, can be used to install the driver without the PC needing to access the web for the driver. Is this what the difference is between the UNO/Mega and the older devices? If so, is it possible to modify, or flash the firmware of the older boards so that they can connect without the need for an FTDI driver?</p>
| <p>The older Arduino boards used an FTDI FT232R chip to handle the USB port. This chip is a special purpose, USB to serial UART interface.</p>
<p>In the current Arduino boards, the USB to serial conversion is handled by dedicated <a href="http://www.atmel.com/devices/ATMEGA8U2.aspx" rel="nofollow">Atmel Atmega8u2</a> processor. This is a processor that is similar to the main ATmega328p processor, but the added benefit of having built-in USB capabilities.</p>
<p>So, why the change? Well, first, it's cheaper than the FTDI chip, and second, it can do much more. Being that it's an actual microprocessor, you can actually reprogram this chip to behave like different USB devices. For example, you can reprogram it to make your Arduino look like a keyboard, a joystick, a thumb drive, a MIDI instrument - anything that you can do via USB. The FTDI chip does not have this capability, and so it can only ever look like a serial COM port to your PC.</p>
<p>Why have 2 microprocessors on the Arduino? By having a dedicated processor to handle the USB communication, it keeps the main processor free to run your sketches. Plus, the Arduino team felt that this design keeps the Arduino more "hackable".</p>
<p>Wouldn't it be cheaper to make a board using just the one processor that has built-in USB? Yes! That is exactly what the Arduino Leonardo is. It uses the Atmega32U2, the big brother to the Atmega8U2.</p>
|
9308 | |arduino-yun|web-server| | Arduino YUN server crashes after few hours! | 2015-03-14T13:53:06.893 | <p>I have made a simple server using the YUN SERVER and CLIENT Libraries./
The server runs on a loop and waits for a client to connect. After connection it sends the client a simple message and then disconnects the client.</p>
<pre><code>#include <Bridge.h>
#include <YunServer.h>
#include <YunClient.h>
#define PORT 6666
YunServer server(PORT);
int pin =13;
void setup() {
Serial.begin(115200);
Bridge.begin();
server.noListenOnLocalhost();
server.begin();
}
void loop() {
YunClient client = server.accept();
if(client.connected())
{
digitalWrite(pin,HIGH);
//startup
startup_msg(client);
}
else
digitalWrite(pin,LOW);
delay(500);
}
void startup_msg(YunClient client)
{
client.print("SAndTerm");
client.stop();
}
</code></pre>
<p>Well this code runs smoothly for few hours. But after that, it stops responding to any client request. I guess the server crashes.
I have to restart the YUN to get it working again.</p>
<p>Is there anyway I can run this without it getting to crash?
Well I want it to be running just like a normal server would.</p>
| <p>Updating your YUN might solve this problem. It is recommended to update it after you buy it because they usually come with old firmware. Make sure its up to date.
<a href="http://arduino.cc/en/Tutorial/YunSysupgrade" rel="nofollow">Here a link on how to do this</a></p>
<p>Another thing to try is to add <code>delay(50);</code> at the end of the <code>loop()</code> function. It prevents the processor from doing lots of work.</p>
|
9315 | |shields|ethernet|atmega328| | Ethernet Shield on Arduino Mini | 2015-03-14T19:57:06.557 | <p>I would like to connect my custom-made Arduino with an Ethernet shield but I'm not so sure I can.</p>
<h2>The problem</h2>
<p>My board is using the design from the Arduino Mini which lacks the <code>ATmega16U2</code> which does the USB-to-serial conversion and adds the <code>ICSP</code> pins. I think you get the point... I have only the <code>ATmega328P</code> on the board. Nothing else.</p>
<p>Is it even possible to work my way around it without adding the <code>ATmega16U2</code>? I can't find the chip anywhere on Ebay.</p>
| <p>You can just connect the pins used on the shield the the corresponding pins on your custom board. Check the <a href="http://arduino.cc/en/uploads/Main/arduino-ethernet-shield-06-schematic.pdf" rel="nofollow">Schematic</a> to see what pins are used for what (and which can be left unconnected)</p>
<p><strike>The only thing you need to lookout for is, that the ethernets shield seems to require 3.3v</strike> (the shield has it's own 3.3v regulator, so you only need to connect 5v)</p>
<p>That 16u2 doesn't do anything but usb-to-serial. It's not needed for the ethernet shield.</p>
<p>The ISP header is just 5v, GND, and the 3 SPI pins and reset. But those SPI pins are also broken out to the pins 11, 12 and 13.</p>
|
9319 | |c++|class| | How to dynamically switch between between 2 objects? | 2015-03-15T00:30:40.163 | <p>I have a 40x4 LCD which internally consists of 2 40x2 LCDs.
To control this LCD I have to create 2 <code>LiquidCrystal</code> objects and than later on in code decide which one to use depending on which of the 4 lines I want to change.</p>
<p>Due to the size of my project, I split all the LCD handling off to a separate class.
To make my code as readable and easy as possible, I want to create a member method of this class, to which I can just pass line number 1-4, and have this method take care of deciding which <code>LiquidCrystal</code> object to use.</p>
<p>LCDController.h:</p>
<pre><code>#include <LiquidCrystal.h>
class LCDControllerClass
{
protected:
public:
void init(LiquidCrystal* Clcd1, LiquidCrystal* Clcd2);
private:
void _UpdateLCD(int _iLine, int _iPosition, String _strText, int _iFieldLength);
LiquidCrystal* _Clcd1;
LiquidCrystal* _Clcd2;
};
extern LCDControllerClass LCDController;
</code></pre>
<p>My 2 <code>LiquidCrystal</code> objects are initialized in my main .ino file like so (before the <code>setup()</code> loop)
:</p>
<pre><code>LiquidCrystal lcd(12, 11, 7, 6, 5, 4); //declare two LCD's
LiquidCrystal lcd2(12, 10, 7, 6, 5, 4); // Ths is the second
</code></pre>
<p>These two objects are then passed as pointers to my <code>LCDControllerClass</code> like so:</p>
<pre><code>LCDController.init(&lcd, &lcd2);
</code></pre>
<p>The <code>init()</code> member method of my <code>LCDControllerClass</code> then puts these pointers in private variables like so:</p>
<pre><code>void LCDControllerClass::init(LiquidCrystal* Clcd1, LiquidCrystal* Clcd2)
{
_Clcd1 = Clcd1;
_Clcd1->begin(40, 2);
_Clcd1->clear();
_Clcd2 = Clcd2;
_Clcd2->begin(40, 2);
_Clcd2->clear();
}
</code></pre>
<p>Then I have another private member method which should take care of updating the correct LCD object:</p>
<pre><code>void LCDControllerClass::_UpdateLCD(int _iLine, int _iPosition, String _strText, int _iFieldLength)
{
LiquidCrystal* CActiveLCD;
if (_iLine > 2)
{
//DisplayLine is higher than 2, this means we need to update the 2nd LCD
LiquidCrystal** CActiveLCD = &_Clcd2;
_iLine = _iLine - 2; //Convert line number to correct line number for 2nd display
}
else
{
//LiquidCrystal** CActiveLCD = &_Clcd1;
}
/* we have to convert this number
to a real display line (0-1) by substracting 1 again
*/
_iLine = _iLine - 1;
CActiveLCD->setCursor(_iPosition, _iLine);
CActiveLCD->print(_strText);
}
</code></pre>
<p>Now in this last member mehthor my code goes into the woods for some reason. The LCD is not updated at all and it seems the arduino is freezing as well since I put a small <code>Serial.print()</code> test in the main loop and it's not printing anything...</p>
<p>What is the correct way to pass the correct <code>LiquidCrystal</code> object to the <code>CActiveLCD</code>
object?</p>
| <p>The problem is that you're declaring multiple pointer variables called <code>CActiveLCD</code> in the <code>_UpdateLCD()</code> function. You do it once at the start of the function like this:</p>
<pre><code>LiquidCrystal* CActiveLCD;
</code></pre>
<p>You then declare a new and <strong>totally separate</strong> pointer inside the <code>if</code> block like this:</p>
<pre><code>LiquidCrystal** CActiveLCD = &_Clcd2;
</code></pre>
<p>This is called masking. The original pointer you declared at the start of the function still exists, but you can't access it because it's temporarily replaced by the new one. When the <code>if</code> block finishes, that new pointer is destroyed (it goes out of scope) and the old one is available again.</p>
<p>All of that means you never actually store a value in the original pointer variable. The result is that it contains an arbitrary memory address, so attempting to use it at the end of the function results in undefined behaviour.</p>
<p>When you are assigning to the pointer inside your <code>if</code> block, you need to do it like this:</p>
<pre><code>CActiveLCD = _Clcd2;
</code></pre>
<p>Notice that this doesn't declare a new <code>CActiveLCD</code> pointer. It simply copies <code>_Clcd2</code> into the existing one. Additionally, it's important not to use the address-of operator here (<code>&</code>). Adding that in this context gives you a pointer-to-a-pointer. It is technically legitimate in C++, and sometimes does serve a useful purpose, but it's not what you want to do here.</p>
<p>As a side note, when declaring a pointer variable it's usually a good idea to initialise it to something. If you're not assigning an actual address to it right away then initialise it to <code>0</code>, like this:</p>
<pre><code>LiquidCrystal* CActiveLCD = 0;
</code></pre>
<p>This means you can check the pointer later on before using it. If it's <code>0</code> then you know it's not got a valid address yet so it's not safe to use. This isn't always strictly necessary, but it can help avoid some frustrating bugs.</p>
|
9352 | |arduino-uno|sd-card| | "write" function in sd card is not working | 2015-03-15T10:17:04.817 | <p>I have recently started working with arduino UNO and the "write" function in sd Card library is not working. Below is my code. I have tried with "println" which is working fine. Any help regarding this is welcome.</p>
<pre><code>void loop()
{
byte b=10;
File dataFile = SD.open("datalog.txt", FILE_WRITE);
if (dataFile)
{
dataFile.write(b);
}
}
</code></pre>
| <p>The problem is that <code>print()</code> and <code>write()</code> behave differently when you give them numerical data, such as a byte.</p>
<p>When you pass your byte to <code>print()</code>, it converts it to text which is convenient for humans to read. For example:</p>
<pre><code>byte b = 10;
dataFile.print(b);
</code></pre>
<p>This will result in the following ASCII characters being written to the file:</p>
<pre><code>10
</code></pre>
<p>That's actually two bytes: one byte with the value 49, which represents ASCII character <code>1</code>, followed by a byte with the value 48 representing character <code>0</code>.</p>
<p>However, <code>write()</code> does <strong>not</strong> convert numbers into text. It writes them in their raw binary form. For example:</p>
<pre><code>byte b = 10;
dataFile.write(b);
</code></pre>
<p>When you do this, it doesn't write a "1" and a "0" to the file. It literally writes a binary byte with the value 10. When you try to open this as a text file, your computer interprets that byte as a single ASCII character. It so happens that ASCII value 10 is the newline character, meaning your file basically contains a blank line.</p>
<p>For comparison, try this instead:</p>
<pre><code>byte b = 65;
dataFile.write(b);
</code></pre>
<p>ASCII value 65 corresponds to the letter <code>A</code> (uppercase), so that's what you should see in the file.</p>
<p>The <code>write()</code> functions are useful for writing raw data to file in the most efficient form for another machine to read (as opposed to being human-readable). This is why they allow you to write arrays -- it acts like one big block of raw data with a fixed format.</p>
<p>In your case, <code>print()</code> is more appropriate. That means for outputting arrays of numbers, you will need to use loops. That functionality isn't built-in to the <code>print()</code> functions because different projects might need different formatting. For example, some people might want one number per line, whereas others might want numbers separated by commas, and so on.</p>
|
9353 | |arduino-uno|serial|arduino-mega|atmega328| | 16Hertz Uno R3 Board vs Arduino Uno R3 Board | 2015-03-15T10:24:35.403 | <p>I bought a <a href="http://www.16hertz.com/product/uno-r3-kit-ultimate-arduino-compatible/" rel="nofollow">16Hertz Uno R3 Board</a>. When I installed the driver and the Arduino IDE, in the IDE`s menu I saw: </p>
<blockquote>
<p>Tools -> Board -> Arduino Uno</p>
</blockquote>
<p>was selected by default which is great, but... </p>
<blockquote>
<p>Tools -> Port -> COM3(Arduino Mega or Mega 2560)</p>
</blockquote>
<p>was selected by default which I think might be some kind of misunderstanding... </p>
<p>When I chose: </p>
<blockquote>
<p>Tools -> Board -> Arduino Mega or Mega 2560</p>
</blockquote>
<p>On that tools menu appeared new menu "Processor" with two options: </p>
<blockquote>
<p>Tools -> Processor -> ATmega2560 (Mega 2560)</p>
</blockquote>
<p>which was selected by default and there was another option</p>
<blockquote>
<p>Tools -> Processor -> ATmega1280</p>
</blockquote>
<p>When I restore Tools -> Board settings back to "Arduino Uno" the "Processor" menu with the two options disappeared and Tools -> Port setting did not changed!</p>
<p>If you take my board and look at the Microcontroller there is written: </p>
<blockquote>
<p>ATMEGA328P-PU</p>
</blockquote>
<p>Also on that board is written: </p>
<blockquote>
<p>16HzUNO</p>
</blockquote>
<p>I need to know: </p>
<ol>
<li>What does 16Hz mean? Does it mean the clock or frequency of this
Microcontroller? I think it does not, if I try to find out details of my Microcontroller on the <a href="http://ie.rs-online.com/web/p/microcontrollers/6962260/" rel="nofollow">rs-online site</a>, there is written: </li>
</ol>
<blockquote>
<p>ATMEGA328P-PU, 8 bit AVR Microcontroller 20MHz 1 kB, 32 kB Flash, 2
kB RAM, I2C 28-Pin PDIP</p>
</blockquote>
<ol start="2">
<li>Why was there "COM3(Arduino Mega or Mega 2560)" written on the
Port's menu?</li>
<li>Is my 16Hz Uno R3 and the Arduino Uno R3 board the same? Which one
is better? When one of those is better?</li>
<li>Does the standard Arduino Uno R3 board have the same ATMEGA328P-PU
Microcontroller?</li>
</ol>
| <p>Just a theory for 2:</p>
<p>The text that shows up in the Tools > Port list after the COMx</p>
<p>eg <code>Tools -> Port -> COM3(Arduino Mega or Mega 2560)</code></p>
<p>is simply what the IDE thinks the board is based on the USB ID (VID/PID) of the board's USB interface chip. For some clones, this is blank because they don't even use the same chip as an authentic Uno. In your case, I would suspect that they have used the USB chip from a Mega board on your Uno board.</p>
<p>So the IDE thinks a Mega is attached because it is seeing a USB chip from a Mega, even though it is an Uno (clone).</p>
|
9366 | |led|attiny|shift-register| | Arduino on attiny85 driving 4-digit 7-segment using two 74HC595N shift register not alternating fast enough | 2015-03-16T03:35:51.157 | <p>I am using a port of the Arduino libraries on an AtTiny85 (1MHz) to drive a 4-digit 7-segment LED (common cathode, 12-pin). I'm just counting from 0 to 9 and alternating between the first two digits (pin 12 and 9) as a test. I am driving from two 74HC595N shift registers in series, the first of which will trigger S9018 NPN BJT transistors to turn on/off the digit I want and the other to light the segments.</p>
<p>The code seems to work fine, functionally, to alternate the two digits, but they don't alternate fast enough to make the LED show two solid digits, instead you can clearly see them flashing/alternating. Not sure what the bottleneck is but here's the code (please ignore my wiring for the 7 segments)</p>
<pre class="lang-c prettyprint-override"><code>// CONFIGURATION
// Pins
const int latchPin = 2;
const int clockPin = 4;
const int dataPin = 3;
// Timers
const long output_interval = 10000; // Time to change each output
const int T_digit = 2; //period on one digit (4 digit 7-segment only)
const int duty_digit = 1; // duty cyle of a digit shown
// States
unsigned long outputT_last = 0; // Holds the last time output change was checked
unsigned long outputT_now = 0;
bool fourDigit7Segment_enable = true; // set if we are using 4 digit 7 segment led
// States
byte leds = 0;
byte digits = 0;
int output_count=0;
void setup()
{
pinMode(latchPin, OUTPUT);
pinMode(dataPin, OUTPUT);
pinMode(clockPin, OUTPUT);
}
void loop()
{
checkOutput();
}
void updateShiftRegister()
{
digitalWrite(latchPin, LOW); // Gets latch ready by setting to low since we need a rising edge to trigger
if(fourDigit7Segment_enable){
int digitON = (int)(outputT_now - outputT_last);
digits = 0;
if(digitON%T_digit < duty_digit){
//bitwrite led 0
bitWrite(digits, 0, 1);
}
else{
//bitwrite led 1
bitWrite(digits, 1, 1);
}
//shift out digit control first in LSB
shiftOut(dataPin, clockPin, MSBFIRST, digits); // shiftOut will write to dataPin and trigger a rising on clickPin at same time while writing byte value from leds var
}
shiftOut(dataPin, clockPin, MSBFIRST, leds); // shiftOut will write to dataPin and trigger a rising on clickPin at same time while writing byte value from leds var
digitalWrite(latchPin, HIGH); // Trigger with rising edge
}
void clearMemory(){
leds = 0;
updateShiftRegister();
}
void checkOutput(){
outputT_now = millis();
float timeleft = (int)((outputT_now - outputT_last)/1000);
if (outputT_now - outputT_last >= output_interval){
outputT_last = outputT_now; // output_interval set to 10000, because LED counts 0 to 9, and then needs to reset
}
// clearMemory(); // Uncomment this if you want 1 LED lit at time, all others turned off
leds = sevenSegment1D(timeleft);
updateShiftRegister();
// output_count++;
// }
// Check if we reach the end, then do 1 more iteration for 0x0 (all turned off)
// if(output_count > 8){
// output_count=0;
// clearMemory();
// }
}
byte sevenSegment1D(int i){
switch (i) {
case 0:
return 0x7E; //01111110
break;
case 1:
return 0x48; //01001000
break;
case 2:
return 0x3D; //00111101
break;
case 3:
return 0x6D; //01101101
break;
case 4:
return 0x4B; //01001011
break;
case 5:
return 0x67; //01100111
break;
case 6:
return 0x77; //01110111
break;
case 7:
return 0x4C; //01001100
break;
case 8:
return 0x7F; //01111111
break;
case 9:
return 0x6F; //01101111
break;
default:
return 0x0; //Arduino doesn't handle bytes in binary
}
}
</code></pre>
<p>I tried to mod a float but it seems to require an int, so that's why I stopped at 2%1. I also converted the code from a single-digit 7-segment LED so please ignore anything that doesn't make sense in lighting up the segments.</p>
<p>I am not sure if the bottleneck is my code, the 1MHz AtTiny85, or the shift register.</p>
<p>EDIT: switched over to <code>micros()</code> instead of using <code>millis()</code> for more resolution. Still not solid.</p>
| <p>The original idea was to divide up a specific period into segments where each digit on the 4-digit 7-segment would light up. I would use a mod(%) and divide it up to make the function call more generic for future extensibility (and also make it more asynchronous). What I learned is that it would probably take more work doing the calculations then just calling a function to reset and light up the next digit one after another. Here's the updated code:</p>
<pre><code>// CONFIGURATION
// Pins
const int latchPin = 2;
const int clockPin = 4;
const int dataPin = 3;
// Timers
const int countdown = 60; // amount of time to countdown from in seconds
const long reset_interval = countdown*1000000; // interval before reset in microseconds, i.e. if countdown is set to 60s, every 60 seconds will reset display to countdown start
// States
unsigned long last_display_update_time = 0; // Holds the last time output change was checked
unsigned long curr_time = 0;
bool fourDigit7Segment_enable = true; // set if we are using 4 digit 7 segment led
// States
byte leds = 0;
byte digits = 0;
int output_count=0;
void setup()
{
pinMode(latchPin, OUTPUT);
pinMode(dataPin, OUTPUT);
pinMode(clockPin, OUTPUT);
}
void loop()
{
updateResetTimer(); // checks what the countdown is at
int timeleft = countdown - (curr_time - last_display_update_time)/1000000;
leds = getSevenSegmentFormation(timeleft/10);
updateShiftRegister(0);
leds = getSevenSegmentFormation(timeleft%10);
updateShiftRegister(1);
}
void updateShiftRegister(int digit)
{
digitalWrite(latchPin, LOW); // Gets latch ready by setting to low since we need a rising edge to trigger
if(fourDigit7Segment_enable){
int digitON = micros();
digits = 0;
bitWrite(digits, digit, 1);
//shift out digit control first in LSB
shiftOut(dataPin, clockPin, MSBFIRST, digits); // shiftOut will write to dataPin and trigger a rising on clickPin at same time while writing byte value from leds var
}
shiftOut(dataPin, clockPin, MSBFIRST, leds); // shiftOut will write to dataPin and trigger a rising on clickPin at same time while writing byte value from leds var
digitalWrite(latchPin, HIGH); // Trigger with rising edge
}
//Turns off all 7 segments of a digit, will need to specify digits 0 to n
void clearMemory(int i){
leds = 0;
updateShiftRegister(i);
}
//Updating timer for resetting countdown
//Will take absolute current time and compare it to the last time checked, if it is greater than countdown value, we reset
void updateResetTimer(){
curr_time = micros();
if (curr_time - last_display_update_time >= reset_interval){
last_display_update_time = curr_time; // reset_interval set to 10000000, because LED counts 0 to 9, and then needs to reset // actually set to 60*1000000 to countdown 1 minute
}
}
byte getSevenSegmentFormation(int i){
switch (i) {
case 0:
return 0x7E; //01111110
break;
case 1:
return 0x48; //01001000
break;
case 2:
return 0x3D; //00111101
break;
case 3:
return 0x6D; //01101101
break;
case 4:
return 0x4B; //01001011
break;
case 5:
return 0x67; //01100111
break;
case 6:
return 0x77; //01110111
break;
case 7:
return 0x4C; //01001100
break;
case 8:
return 0x7F; //01111111
break;
case 9:
return 0x6F; //01101111
break;
default:
return 0x0; //Arduino doesn't handle bytes in binary
}
}
</code></pre>
|
9377 | |timers|isr| | Why does timer ISR not execute? | 2015-03-16T10:12:08.810 | <p>This is my code which I have written as a library </p>
<pre><code>#include "avr/interrupt.h"
#include "Arduino.h"
#include "AllTimer.h"
AllTimer::AllTimer()
{}
void AllTimer::dofun(void)
{
//TIFR1 |= _BV(OCF1A);
TCCR1B = 0X00;
//TIFR1 = 0X01;
digitalWrite(13,!digitalRead(13));
Serial.print("I printed");
TCNT1 = 0X0000;
TCCR1B |= (1<<CS12) && (1<<CS10);
//sei();
}
void AllTimer::setTimer(void)
{
TCNT1 = 0x0000;
TCCR1A = 0x00;
TCCR1B = 0x00;
TCCR1B |= (1<<CS12) && (1<<CS10);
TIMSK1 |= (1<<TOIE1);
sei();
}
ISR (TIMER1_OVF_vect)
{
AllTimer::dofun();
}
</code></pre>
<p>Code in Arduino IDE:</p>
<pre><code> #include <AllTimer.h>
AllTimer mytimer;
void setup()
{
pinMode(13,OUTPUT);
Serial.begin(9600);
}
void loop()
{
mytimer.setTimer();
//delay(200);
}
</code></pre>
<p>But I am not getting anything on the serial monitor. What is the error I have made?</p>
| <p>The Arduino <code>main()</code> calls <code>loop()</code> continuously, in a tight loop. Thus
your <code>AllTimer::setTimer()</code> is called continuously, and each time it
resets the counter (<code>TCNT1 = 0x0000;</code>). Thus the counter can never
overflow.</p>
|
9382 | |arduino-uno|atmega328|linux| | Arduino Uno R3 USB is not working | 2015-03-16T12:00:04.533 | <p>I have a problem with my Arduino Uno board. It's not mounting in my Linux machine, but its power is <em>on</em> and the LED light is glowing. It was working before. After I tested buttons with an 12 V external supply, I am facing this scenario.</p>
<p>I tried <code>lsusb</code> and I checked <code>/dev/ ports</code>. Also, I couldn't find `ttyACM. I tried with another Arduino board and it's working. I think the board is gone, and I need help to fix this problem.</p>
<p>I thought it was a bootloader problem, and I got a <em>new ATmega328P chip board</em>. It is getting power on and the LED is blinking, but the port is not mounted. I tried with <code>lsusb</code> and also <code>ls /dev/ttyACM*</code> with no result.</p>
| <p>Maybe you need to "reflash" the FTDI firmware. Sorry, I'm very bad in Linux. To do this, you'll need some software and a HEX file. Check this video on YouTube:</p>
<p><em><a href="http://www.youtube.com/watch?v=fSXZMVdO5Sg" rel="nofollow noreferrer">ARDUINO- Upgrading USB FIRMWARE using FLIP</a></em></p>
<p>And download the <em>arduino_usbtoserial.hex</em> file.</p>
<p>If it doesn't work, and if your Arduino Uno has the ATmega328P chip as <a href="https://en.wikipedia.org/wiki/Dual_in-line_package" rel="nofollow noreferrer">DIP</a>, try to change the ATmega328P chip in the board. Remove this chip carefully. Put another chip in with the bootloader and test.</p>
|
9385 | |arduino-uno|power| | Can I safely connect my original Arduino Uno to a 19V adapter? | 2015-03-16T14:25:20.167 | <p>I have an original Arduino Uno R3. According to the <a href="http://www.arduino.cc/en/Main/arduinoBoardUno" rel="nofollow">specifications</a> the recommended input voltage is 7 to 12 Volt.</p>
<p>However, I have a laptop adapter of 19V that I want to use to power my arduino because it offers more current than the 9V adapter I have as well.</p>
<p>I don't want to damage the Arduino or the <a href="http://www.dfrobot.com/index.php?route=product/product&product_id=69" rel="nofollow">DFRobot 2A Motor Shield</a> I'm using. Can I safely plug in the adapter and will it still work correctly?</p>
| <p>It's often better to supply separate power to high-current applications (such as motors) rather than taking power off the Arduino. This avoids problems with current and thermal limits of the Arduino on-board power regulator.</p>
<p>Looking at the <a href="https://www.dfrobot.com/wiki/index.php/Arduino_Motor_Shield_(L298N)_(SKU:DRI0009)" rel="nofollow noreferrer">manual for your board</a>, the motors can be powered by a separate power supply hooked up directly to the motor shield. There's a six-pin header on the board marked VIN and PWRIN. When the jumpers are on the VIN side Arduino-supplied power is used to drive the motors; when the jumpers are on the PWRIN side the motors are supplied with power from the terminal block next to the jumper. (The rest of the board remains powered from the Arduino, but that's usually a negligible amount of current compared to your motors.) A photo in the manual demonstrates the pins set to PWRIN and an external power supply hooked up.</p>
<p>The documentation says you can supply any voltage between 4.8 V and 35 V DC, but <strong>be careful!</strong> What they don't make clear in the documentation (but is clear from the <a href="http://image.dfrobot.com/image/data/DRI0009/Arduino%20L298%20Shield%20Sch.pdf" rel="nofollow noreferrer">schematic</a> and the <a href="http://image.dfrobot.com/image/data/DRI0009/L298N%20datasheet.pdf" rel="nofollow noreferrer">L298N datasheet</a>) is that this power is supplied directly to power side of the L298N and the motors without further regulation. The chip can handle up to 50 V DC, so it would be fine with a 35 V input, but you'll want to check that your motors can handle the voltage you want to give them.</p>
<p>If the motors can handle 19 V input, and your 19 V power supply is reasonably well regulated itself (which a laptop computer power supply generally would be), you can use that to power the motors directly through the motor shield and continue using your current power supply to power the Arduino.</p>
<p>(The <a href="http://www.st.com/en/motor-drivers/l298.html" rel="nofollow noreferrer">ST L298</a> page has further information, including a slightly less readable copy of the data sheet and application notes.)</p>
|
9388 | |serial|arduino-mega|i2c|interrupt|timers| | Reading I2C sensors with a timer interrupt | 2015-03-16T15:43:18.597 | <p>I would like to read a sensor connected via I2C using Timer3 and Arduino Mega. Values are read from the sensor in the interrupt service routine and timer3 is set to trigger an interrupt at 200Hz.</p>
<p><strong>Step I: testing the timer</strong></p>
<p>I tested the timer using a counter and incrementing its value in the ISR. The output is displayed every second. It works!</p>
<pre><code>200
201
200
201
</code></pre>
<p><strong>CODE</strong></p>
<pre><code>// Timer variable
volatile int cont=0;
void setup()
{
Wire.begin();
Serial.begin(115200);
setupL3G4200D(2000); // Configure L3G4200 - 250, 500 or 2000 deg/sec
delay(1500); //wait for the sensor to be ready
// Initialize Timer
cli();
TCCR3A = 0;
TCCR3B = 0;
// Set compare match register to the desired timer count
OCR3A=77; //16*10^6/(200Hz*1024)-1 = 77 -> 200 Hz
//OCR3A=193; //16*10^6/(80Hz*1024)-1 = 194 -> 80 Hz
TCCR3B |= (1 << WGM32);
// Set CS10 and CS12 bits for 1024 prescaler:
TCCR3B |= (1 << CS30) | (1 << CS32);
// enable timer compare interrupt:
TIMSK3 |= (1 << OCIE3B);
// enable global interrupts:
sei();
k = micros();
}
void loop()
{
delay(1000);
Serial.println(cont);
cont=0;
}
ISR(TIMER3_COMPB_vect)
{
cont++;
}
</code></pre>
<p><strong>Step II: Reading values from the sensor in the ISR</strong></p>
<p>Now I add the I2C function in the Interrupt Service Routine, but the program is blocked after the calcBias() function which reads from the sensor, measures and saves the acquisition time in the samplingTime variable.</p>
<p><strong>CODE</strong></p>
<pre><code>// Timer variables
volatile float phi=0;
volatile float theta=0;
volatile float psi=0;
volatile int x = 0;
volatile int y = 0;
volatile int z = 0;
volatile int cont=0;
void setup()
{
Wire.begin();
Serial.begin(115200);
setupL3G4200D(2000); // Configure L3G4200 - 250, 500 or 2000 deg/sec
delay(1500); //wait for the sensor to be ready
calcBias():
Serial.print("Readings take: (us)");
Serial.println(samplingTime);
// Initialize Timer
cli();
TCCR3A = 0;
TCCR3B = 0;
// Set compare match register to the desired timer count
OCR3A=77; //16*10^6/(200Hz*1024)-1 = 77 -> 200 Hz
//OCR3A=193; //16*10^6/(80Hz*1024)-1 = 194 -> 80 Hz
TCCR3B |= (1 << WGM32);
// Set CS10 and CS12 bits for 1024 prescaler:
TCCR3B |= (1 << CS30) | (1 << CS32);
// enable timer compare interrupt:
TIMSK3 |= (1 << OCIE3B);
Serial.println("Enabling interrupts..");
// enable global interrupts:
sei();
k = micros();
}
void loop()
{
delay(1000);
Serial.println(cont);
Serial.println(z);
cont=0;
}
ISR(TIMER3_COMPB_vect)
{
// Update x, y, and z with new values 2.5ms
getGyroValues();
cont++;
}
void getGyroValues()
{
//starting samplingTimer
samplingTime = micros();
// Gets the angular velocity from the sensor
byte zMSB = readRegister(L3G4200D_Address, 0x2D);
byte zLSB = readRegister(L3G4200D_Address, 0x2C);
z = ((zMSB << 8) | zLSB);
samplingTime = micros()- samplingTime;
}
void calcBias()
{
Serial.println("Bias");
// Reads sensors and display three values
getGyroValues();
[...]
Serial.println(bx);
Serial.println(by);
Serial.println(bz);
}
void writeRegister(int deviceAddress, byte address, byte val)
{
Wire.beginTransmission(deviceAddress); // start transmission to device
Wire.write(address); // send register address
Wire.write(val); // send value to write
Wire.endTransmission(); // end transmission
}
int readRegister(int deviceAddress, byte address)
{
int v;
Wire.beginTransmission(deviceAddress);
Wire.write(address); // register to read
Wire.endTransmission();
Wire.requestFrom(deviceAddress, 1); // read a byte
while(!Wire.available())
{
// waiting
// Serial.println("No Data");
}
v = Wire.read();
return v;
}
</code></pre>
<p>I thought that the interrupt frequency was to high and I tried with 80 Hz and 20 Hz. Same results.</p>
<p>Here is the output:</p>
<pre><code>starting up L3G4200D
Bias
4.00
0.00
-3.00
Read
</code></pre>
| <p>I2C requires interrupts to work, however enabling interrupts inside an ISR is <strong>not recommended</strong>. For one thing you may get into a race condition, where another interrupt occurs while processing the existing one. </p>
<p>Since you are doing virtually nothing in your main loop, a more sensible design would be to simply test if it is time to take a reading, and when that time is up, take the reading then.</p>
<p>As an example, your main loop could be rewritten as:</p>
<pre class="lang-C++ prettyprint-override"><code>unsigned long lastReading;
unsigned long lastDisplay;
void loop()
{
if (millis () - lastReading >= 5) // 200 Hz
{
lastReading = millis ();
// Update x, y, and z with new values 2.5ms
getGyroValues();
cont++;
}
if (millis () - lastDisplay >= 1000) // one second
{
lastDisplay = millis ();
Serial.println(cont);
Serial.println(z);
cont=0;
}
}
</code></pre>
<p>Now you don't need the timer, and you are interrupt-friendly. :)</p>
<p>More information about interrupts: <a href="http://www.gammon.com.au/interrupts" rel="nofollow">http://www.gammon.com.au/interrupts</a></p>
|
9406 | |arduino-motor-shield| | Connect 5V DC Fan to Ardumoto | 2015-03-17T07:43:45.227 | <p>I wish to connect 2 simple 5V DC Brushless Fan (80x80x15mm, <a href="https://www.sparkfun.com/products/9649" rel="nofollow">https://www.sparkfun.com/products/9649</a>) to Ardumoto (<a href="https://www.sparkfun.com/products/9815" rel="nofollow">https://www.sparkfun.com/products/9815</a>).</p>
<p>Therefore, how to I turn on/off the fan as I do not know how to address it? Do I need to connect a power supply to the Ardumoto, to the Arduino board or 2 separate power supplies to each one of them?</p>
<p>Thanks.</p>
| <p>If you look at the <a href="https://www.sparkfun.com/datasheets/DevTools/Arduino/Ardumoto_v13.pdf" rel="nofollow">schematic</a> on the product page it shows that the <code>Vin</code> from the arduino is connected to the same Vin on the shield and the Vin to the motor driver. So it is either or where you want to connect power.</p>
<p>With regards to controlling the fan, brushless fans are polarized because of the internal control circuitry, this means that <strong>it cannot be made to reverse</strong>, therefore you should always give the direction pin a high signal. The <a href="https://learn.sparkfun.com/tutohttps://learn.sparkfun.com/tutorials/ardumoto-shield-hookup-guiderials/ardumoto-shield-hookup-guide" rel="nofollow">Sparkfun hookup guide</a> has a example code which shows how to control the motor shield, and some explination.</p>
|
9410 | |sensors| | How to: soil moisture measurement with WaterMark? | 2015-03-17T10:34:58.837 | <p>I am new with Arduino, and i cant find documentation about how to connect Arduino with Watermark successfully.</p>
<p>I would like to connect my Arduino UNO with a watermark like this:</p>
<p><a href="http://guideimg.alibaba.com/images/shop/72/08/19/4/watermark-soil-moisture-sensor-w-15-cable_3234944.jpg" rel="nofollow">http://guideimg.alibaba.com/images/shop/72/08/19/4/watermark-soil-moisture-sensor-w-15-cable_3234944.jpg</a></p>
<p>Does anyone know any schema or documentation about how to do it? Have anyone tried it before?</p>
<p>I have found this: <a href="https://oceancontrols.com.au/datasheet/davis/ECS-014_07395-158_IM_06440_6470.pdf" rel="nofollow">https://oceancontrols.com.au/datasheet/davis/ECS-014_07395-158_IM_06440_6470.pdf</a></p>
<p>but still not clear how to do it in Arduino.</p>
<p>Thanks you for your time.</p>
| <p>You can google
"Arduino-based system for soil moisture measurement"
and the author about this paper is "Vuk Radman" .
<a href="https://i.stack.imgur.com/EFwOX.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/EFwOX.png" alt="enter image description here"></a>
Now, I am also try to find the method using Arduino to connect WaterMark 200ss Sensor. The paper I share to you is what I have found from GoogleScholar, but I haven't used this method yet. Nevertheless, I think the method mentioned in the paper is feasible. Hopefully, this information can help you.</p>
|
9416 | |programming|c| | Port manipulation using C code | 2015-03-17T15:32:14.893 | <p>I'm trying to manipulate the ports of Arduino using C code. I have attached an LED to pin 8 and a tact switch to pin 13 (with a pull down resistor). The code works fine, and the results are printed on the screen. So, when the button is pressed, the byte <code>PINB & (1 << PB5)</code> equals 32, or <code>0b00100000</code>. </p>
<p>However, if I try to use</p>
<pre><code>if( PINB &(1<<PB5) == 32){
</code></pre>
<p>or </p>
<pre><code>if( PINB &(1<<PB5) == 0b00100000){
</code></pre>
<p>the LED doesn't respond.</p>
<p>Here's the full code:</p>
<pre><code>void setup() {
DDRB |= 0b00011111;
Serial.begin(9600);
}
void loop() {
Serial.print("PINB &(1<<PB5)");
Serial.println(PINB &(1<<PB5));
if( PINB &(1<<PB5) ){
PORTB |= (1<<PB0);
}
else{
PORTB &= ~(1<<PB0);
}
}
</code></pre>
<p>What am I missing?</p>
| <p><code>==</code> has higher precedence than <code>&</code>, which means that your comparison will be performed incorrectly. But that doesn't matter, since you don't need to check if the port has a <em>specific</em> value, just if the appropriate bit is set.</p>
|
9425 | |arduino-ide| | How do I change the Console colour of Arduino IDE? | 2015-03-17T18:41:46.257 | <p>Leading on from the question <a href="https://arduino.stackexchange.com/questions/4364/can-i-change-font-color-and-or-type-for-ide-1-5-6r2">Can I change font Color and/or Type for IDE 1.5.6r2?</a>, in 1.6.0, or 1.6.1<sup>1</sup> it does not seem to be possible to change <code>console.color</code> or <code>console.error.color</code>. To be precise, you can change the settings in the <code>preferences.txt</code><sup>2</sup> file, but they appear to be ignored when the IDE is restarted. Have these become hard coded? I see from the <a href="https://code.google.com/p/arduino/source/browse/trunk/build/shared/lib/preferences.txt?r=71" rel="nofollow noreferrer">preference.txt example file</a> that </p>
<pre><code># Some colors have been hardcoded into the source in app/ in order to ensure
# consistency with the images distributed and stored with the application.
# They have been commented out below so that users who install an old
# version of the software will not get incorrect colors left-over from this
# config file.
</code></pre>
<p>However, the settings to which I refer are not commented out, and so would led me to believe that they can be changed. Orange text on black is just horrific to read.</p>
<p>For example:</p>
<pre><code>console.error.color=#FFF000
console.color=#FFCCCC
</code></pre>
<p>but I still get white/orange(red?) text for the output and error messages respectively.</p>
<p>I am making the edits while the Arduino IDE is not running. </p>
<hr>
<p><sup>1</sup> In 1.6.3 the ignored <code>console.color</code> etc. lines appear to have been removed from the <code>preferences.txt</code> file. </p>
<p><sup>2</sup> <code>C:\Users\username\AppData\Roaming\Arduino15\preferences.txt</code></p>
| <p>Download the Dark Theme of Jeff Thompson from <a href="https://github.com/jeffThompson/DarkArduinoTheme" rel="nofollow noreferrer">Github: jeffThompson/DarkArduinoTheme</a></p>
<p><a href="https://i.stack.imgur.com/WIcm4.jpg" rel="nofollow noreferrer" title="Jeff Thompson's - Dark Arduino Theme"><img src="https://i.stack.imgur.com/WIcm4.jpg" alt="Jeff Thompson's - Dark Arduino Theme" title="Jeff Thompson's - Dark Arduino Theme"></a></p>
<p>Screenshot:</p>
<p><a href="https://i.stack.imgur.com/O3mQW.png" rel="nofollow noreferrer" title="Screenshot of Jeff Thompson's - Dark Arduino Theme"><img src="https://i.stack.imgur.com/O3mQW.png" alt="Screenshot of Jeff Thompson's - Dark Arduino Theme" title="Screenshot of Jeff Thompson's - Dark Arduino Theme"></a></p>
|
9432 | |led|sketch|shift-register| | Integrating Shift Registers into 7 Segment LED Circuit | 2015-03-17T23:40:35.750 | <p>I'm trying to implement a shift register(s) into my circuitry and program to control two seven segment LEDs that would count up from 00 - 99. So far I have a fairly straightforward code (at least, I think. It's my first time experimenting with creating my own void functions) that controls the 7 segs in this manner, but I end up using every single digital pin on my Uno. Here it is:</p>
<pre><code>const int led1a = 13;
const int led1b = 12;
const int led1c = 11;
const int led1d = 10;
const int led1e = 9;
const int led1f = 8;
const int led1g = 7;
const int led2a = 6;
const int led2b = 5;
const int led2c = 4;
const int led2d = 3;
const int led2e = 2;
const int led2f = 1;
const int led2g = 0;
void setup() {
pinMode(led1a, OUTPUT);
pinMode(led1b, OUTPUT);
pinMode(led1c, OUTPUT);
pinMode(led1d, OUTPUT);
pinMode(led1e, OUTPUT);
pinMode(led1f, OUTPUT);
pinMode(led1g, OUTPUT);
pinMode(led2a, OUTPUT);
pinMode(led2b, OUTPUT);
pinMode(led2c, OUTPUT);
pinMode(led2d, OUTPUT);
pinMode(led2e, OUTPUT);
pinMode(led2f, OUTPUT);
pinMode(led2g, OUTPUT);
}
void loop () {
led1_0();
led2_run();
led1_1();
led2_run();
led1_2();
led2_run();
led1_3();
led2_run();
led1_4();
led2_run();
led1_5();
led2_run();
led1_6();
led2_run();
led1_7();
led2_run();
led1_8();
led2_run();
led1_9();
led2_run();
}
void led1_0() {
digitalWrite(led1a, HIGH);
digitalWrite(led1b, HIGH);
digitalWrite(led1c, HIGH);
digitalWrite(led1d, HIGH);
digitalWrite(led1e, HIGH);
digitalWrite(led1g, HIGH);
digitalWrite(led1f, LOW);
}
void led1_1() {
digitalWrite(led1a, LOW);
digitalWrite(led1b, HIGH);
digitalWrite(led1c, HIGH);
digitalWrite(led1d, LOW);
digitalWrite(led1e, LOW);
digitalWrite(led1f, LOW);
digitalWrite(led1g, LOW);
}
void led1_2() {
digitalWrite(led1a, HIGH);
digitalWrite(led1b, HIGH);
digitalWrite(led1f, HIGH);
digitalWrite(led1e, HIGH);
digitalWrite(led1d, HIGH);
digitalWrite(led1c, LOW);
digitalWrite(led1g, LOW);
}
void led1_3() {
digitalWrite(led1a, HIGH);
digitalWrite(led1b, HIGH);
digitalWrite(led1c, HIGH);
digitalWrite(led1d, HIGH);
digitalWrite(led1f, HIGH);
digitalWrite(led1e, LOW);
digitalWrite(led1g, LOW);
}
void led1_4() {
digitalWrite(led1a, LOW);
digitalWrite(led1b, HIGH);
digitalWrite(led1c, HIGH);
digitalWrite(led1f, HIGH);
digitalWrite(led1g, HIGH);
digitalWrite(led1e, LOW);
digitalWrite(led1d, LOW);
}
void led1_5() {
digitalWrite(led1a, HIGH);
digitalWrite(led1f, HIGH);
digitalWrite(led1g, HIGH);
digitalWrite(led1c, HIGH);
digitalWrite(led1d, HIGH);
digitalWrite(led1b, LOW);
digitalWrite(led1e, LOW);
}
void led1_6() {
digitalWrite(led1a, HIGH);
digitalWrite(led1g, HIGH);
digitalWrite(led1f, HIGH);
digitalWrite(led1c, HIGH);
digitalWrite(led1d, HIGH);
digitalWrite(led1e, HIGH);
digitalWrite(led1b, LOW);
}
void led1_7() {
digitalWrite(led1a, HIGH);
digitalWrite(led1b, HIGH);
digitalWrite(led1c, HIGH);
digitalWrite(led1d, LOW);
digitalWrite(led1e, LOW);
digitalWrite(led1f, LOW);
digitalWrite(led1g, LOW);
}
void led1_8() {
digitalWrite(led1a, HIGH);
digitalWrite(led1b, HIGH);
digitalWrite(led1c, HIGH);
digitalWrite(led1d, HIGH);
digitalWrite(led1e, HIGH);
digitalWrite(led1f, HIGH);
digitalWrite(led1g, HIGH);
}
void led1_9() {
digitalWrite(led1a, HIGH);
digitalWrite(led1b, HIGH);
digitalWrite(led1c, HIGH);
digitalWrite(led1d, HIGH);
digitalWrite(led1g, HIGH);
digitalWrite(led1f, HIGH);
digitalWrite(led1e, LOW);
}
void led2_0() {
digitalWrite(led2a, HIGH);
digitalWrite(led2b, HIGH);
digitalWrite(led2c, HIGH);
digitalWrite(led2d, HIGH);
digitalWrite(led2e, HIGH);
digitalWrite(led2g, HIGH);
digitalWrite(led2f, LOW);
}
void led2_1() {
digitalWrite(led2a, LOW);
digitalWrite(led2b, HIGH);
digitalWrite(led2c, HIGH);
digitalWrite(led2d, LOW);
digitalWrite(led2e, LOW);
digitalWrite(led2f, LOW);
digitalWrite(led2g, LOW);
}
void led2_2() {
digitalWrite(led2a, HIGH);
digitalWrite(led2b, HIGH);
digitalWrite(led2f, HIGH);
digitalWrite(led2e, HIGH);
digitalWrite(led2d, HIGH);
digitalWrite(led2c, LOW);
digitalWrite(led2g, LOW);
}
void led2_3() {
digitalWrite(led2a, HIGH);
digitalWrite(led2b, HIGH);
digitalWrite(led2c, HIGH);
digitalWrite(led2d, HIGH);
digitalWrite(led2f, HIGH);
digitalWrite(led2e, LOW);
digitalWrite(led2g, LOW);
}
void led2_4() {
digitalWrite(led2a, LOW);
digitalWrite(led2b, HIGH);
digitalWrite(led2c, HIGH);
digitalWrite(led2f, HIGH);
digitalWrite(led2g, HIGH);
digitalWrite(led2e, LOW);
digitalWrite(led2d, LOW);
}
void led2_5() {
digitalWrite(led2a, HIGH);
digitalWrite(led2f, HIGH);
digitalWrite(led2g, HIGH);
digitalWrite(led2c, HIGH);
digitalWrite(led2d, HIGH);
digitalWrite(led2b, LOW);
digitalWrite(led2e, LOW);
}
void led2_6() {
digitalWrite(led2a, HIGH);
digitalWrite(led2g, HIGH);
digitalWrite(led2f, HIGH);
digitalWrite(led2c, HIGH);
digitalWrite(led2d, HIGH);
digitalWrite(led2e, HIGH);
digitalWrite(led2b, LOW);
}
void led2_7() {
digitalWrite(led2a, HIGH);
digitalWrite(led2b, HIGH);
digitalWrite(led2c, HIGH);
digitalWrite(led2d, LOW);
digitalWrite(led2e, LOW);
digitalWrite(led2f, LOW);
digitalWrite(led2g, LOW);
}
void led2_8() {
digitalWrite(led2a, HIGH);
digitalWrite(led2b, HIGH);
digitalWrite(led2c, HIGH);
digitalWrite(led2d, HIGH);
digitalWrite(led2e, HIGH);
digitalWrite(led2f, HIGH);
digitalWrite(led2g, HIGH);
}
void led2_9() {
digitalWrite(led2a, HIGH);
digitalWrite(led2b, HIGH);
digitalWrite(led2c, HIGH);
digitalWrite(led2d, HIGH);
digitalWrite(led2g, HIGH);
digitalWrite(led2f, HIGH);
digitalWrite(led2e, LOW);
}
void led2_run() {
led2_0();
delay(1000);
led2_1();
delay(1000);
led2_2();
delay(1000);
led2_3();
delay(1000);
led2_4();
delay(1000);
led2_5();
delay(1000);
led2_6();
delay(1000);
led2_7();
delay(1000);
led2_8();
delay(1000);
led2_9();
delay(1000);
}
</code></pre>
<p>So how would I reduce the amount of pins used while still keeping functionality? I have two 74HC595N shift registers at my disposal.</p>
<p>Thanks!</p>
| <p>I have done exactly this, to great effect.</p>
<pre><code>int clockPin = 4;
int dataPin = 2;
int oePin = 3;
// Here are the digits from 0 to 9, as bitmaps.
// You will need to work out which segments are which,
// according to your wiring, and make your own.
unsigned char digitmaps[]={0x7b,0x11,0xe3,0xb3,0x99,0xba,0xfa,0x13,0xfb,0xbb};
void setup() {
pinMode(clockPin,OUTPUT);
pinMode(dataPin,OUTPUT);
pinMode(oePin,OUTPUT);
}
void sendnumber(unsigned int number, int oePin,int dataPin,int clockPin) {
digitalWrite(oePin,LOW);
shiftOut(dataPin,clockPin,MSBFIRST, digitmaps[(number/10)%10]);
shiftOut(dataPin,clockPin,MSBFIRST, digitmaps[number%10]);
digitalWrite(oePin,HIGH);
}
void loop() {
for (int i=0; i<100; i++) {
sendnumber(i,oePin,dataPin,clockPin);
delay(1000);
}
}
</code></pre>
<p>The crux of the matter is shiftOut, which shifts 8 bits out the dataPin, toggling the clockPin as it goes, high bit first (MSBFIRST), looking up the pattern in the table. dataPin goes to serial in on the FIRST shift register, clockpin to BOTH clocks, oePin to BOTH OE and another one, I think store register? Q7' or QH' (depending on your docs - it's the overflow pin) of the first goes to the serial in of the second, and +5v & GND, as per normal, and the 8 parallel out Q0-Q7 go to the pins on the 7-segment.</p>
<p>If there's anything unclear, or anything I've missed, let me know. My example shows 2 digits, but any number will work, up to the available power.</p>
<p>Things might be clearer if I convert the digitmaps to binary. The below compiles to the same thing as the one above.</p>
<pre><code>unsigned char digitmaps[]={
B01111011, // 0
B00010001, // 1
B11100011, // 2
B10110011, // 3
B10011001, // 4
B10111010, // 5
B11111010, // 6
B00010011, // 7
B11111011, // 8
B10111011}; // 9
</code></pre>
<p>This is because, in my wiring, from left to right the bits represent in the 8 on my display: center,bottom left,bottom,right bottom,top left,decimal point/not used,top,right top. You can see that the digit "1" has 2 1's in it: the 4th (right bottom) and the last (right top). An 8 has all of the bits set to 1, except position 6 - because that's the decimal point. Send individual bits (e.g. B00010000) to see which segments shows up, make a map, and then combine them.</p>
|
9434 | |lcd|arduino-pro-mini| | Flickering LCD when using > 5v power supply on a Pro Mini | 2015-03-18T03:01:22.933 | <p>I have a Pro Mini wired up to an LCD via an I2C board. At <a href="http://www.arduino.cc/en/Main/ArduinoBoardProMini" rel="nofollow">http://www.arduino.cc/en/Main/ArduinoBoardProMini</a> it says the pro mini can accept up to 12v on the RAW pin as it has a voltage regulator on board. When I plug a 12v power supply into the raw pin, the LCD works fine initially, then slowly degrades into flickering more and more. It also does this with a 9v power supply. At 5v it works perfectly. Any ideas what's going on?</p>
| <p>If the LCD has a backlight you are absolutely over heating the regulator on that board by running it at 9 or 12V: At 12V with 100mA for the backlight and using 175C/W thermal resistance for the regulator:
Tj = 25C + ((12V - 5V) x 100mA x 175C/W) = 147C
That regulator goes into thermal limit at 125C.</p>
|
9439 | |gsm|max232| | GSM Modem with MAX232 to Arduino Serial? | 2015-03-18T11:50:29.233 | <p>I have GSM modem that has MAX232 interface for RX/TX/GND on three pins.
Is it possible to interface Arduino in some way?</p>
<p>Tnx for help.</p>
| <p>Yes, with another MAX232, or bypass the MAX232 somehow.</p>
|
9442 | |analogread|system-design| | AVCC and AREF when using a reference voltage lower than 5V? | 2015-03-18T13:40:24.340 | <p>I'm designing a circuit that will use a 2.5v reference for the AREF. Should AVCC be powered from 5V or 2.5V?</p>
| <blockquote>
<p>AVCC is the supply voltage pin for the A/D Converter, PC3:0, and ADC7:6. It should be externally connected to VCC, even if the ADC is not used. If the ADC is used, it should be connected to VCC through a low-pass filter. Note that PC6...4 use digital supply voltage, VCC.</p>
</blockquote>
<p>So it should be connected to 5V.</p>
|
9447 | |sensors|electronics| | Razor 9DOF SMD Capacitor replacing | 2015-03-18T16:25:28.040 | <p>I just bought This IMU a while ago, and when I reached the point where I wanna connect it, I noticed that one of the capacitors have been removed by accedint, and since it took too long to check the product, I won't get to replace it or get any refund, so my question, how can I replace that SMD capacitor?
P.S. I have some Ultrasonic sensors might have the same SMD capacitors that I can take off and replace with if anyone can help.</p>
<p><img src="https://i.stack.imgur.com/08bCC.jpg" alt="The circled capacitor is the one"></p>
| <p>Try using two soldering pencils, one in each hand. makes it easy to remove the capacitor from the donor board.</p>
|
9453 | |programming|c++|sketch| | Using A 4 Ohm Speaker With Arduino | 2015-03-19T02:30:21.827 | <p>I've salvaged a 4 Ohm, 1.5 Watt speaker from an old computer, and I was wondering how I'd go about getting it to work with my Arduino. I've heard of various amplifier circuits such as opamps, but I do not know which would be the best for my situation. I've also heard that using the speaker in certain ways (such as directly connected to a pin from the Arduino) could damage both the speaker and the output pin, so that is definitely something I'd like to avoid. I'm not looking for anything complicated; I'm just trying to get a feel for the general circuitry, programming, and speaker volume. Any suggestions?</p>
| <p>5v, 4ohm, >1amp from a pin rated for 0.04amps; this isn't safe!<br>
You would need a driver, but it would suffice to add a small transistor & a couple of resistors to drive it; <a href="http://hackaweek.com/hacks/?p=327" rel="nofollow">here</a> is a slightly more complex layout, there are many examples on the web.</p>
|
9457 | |arduino-uno|sensors| | Different dht21 readings on different arduinos | 2015-03-19T10:26:12.730 | <p>First of all, let me begin by saying that I'm still pretty much a rookie. </p>
<p>I have a project with a dht21, an LDR and an ultrasonic distance sensor. I have 3 different arduino uno boards, namely: </p>
<ul>
<li>A (supposedly) original arduino uno r3.</li>
<li>A chinese nhduino, arduino uno r3 clone.</li>
<li>And <a href="http://www.banana-pi.net/index.php/en/product/banana-pi/modules/banana-pi-bpiduino-uno-module-detail" rel="nofollow">this</a> one, sitting on top of <a href="http://www.bananapi.org/p/product.html" rel="nofollow">this</a>.</li>
</ul>
<p>I've been playing around with the three boards for the last couple of months, testing a variety of sensors and having the same results with the three boards, as expected. But then, with the aforementioned setup, I'm getting very different readings on the DHT21 sensor. If I use the "regular" (first two) arduinos plugged in my laptop, the readings are consistent. But if I use the banana pi(duino), I get the temperature reading correct, but getting weird humidity readings... pretty most of the time a 5% humidity value.</p>
<p>Everything tested on the same room, same sensors and same protoboard. No external power supply.</p>
<p>I'm totally clueless here, any ideas of what could be the problem?</p>
<p>Thanks.</p>
| <p>Problem solved. Using a ywrobot breadboard PSU and now it works. I haven't tested current in the circuit but looks like it was just too low. I wish I'd had datasheet for the board to look at. In a language different from chinese would have been ok, I guess.</p>
|
9464 | |arduino-uno|atmega328| | What is the rise time of an output pin of atmega328 changing its state? | 2015-03-19T16:45:14.327 | <p>I've already searched a lot and didn't found the answer. Also, I don't have an o'scope. Anyone can help me?</p>
| <p>I got 8 ns on both the rising and falling edges. If using the PORT instruction to set and clear bits instead of the much slower digitalWrite() instruction, the highest frequency I got by toggling a pin high and low was 2.666 Mhz. This is slowed down by the excessive time the arduino takes to pass execution back to the top of the Loop() marker. The duty cycle of the pulse output at 2.666 Mhz was somewhere in the region of 15%.</p>
|
9465 | |arduino-mega|interrupt|pulsein| | Is PulseIn fast enough for Quadcopter? | 2015-03-19T17:36:23.283 | <p>I've been trying to use interrupts to control a quadrotor with a tx/rx to no success. I'm using an arduino mega as my control board. I have successfully read a singe channel using attach interrupt and PulseIn. I have also successfully read multiple channels with pulse but failed to do so with attach interrupt and pinchange int. Should I just go ahead and use PulseIn</p>
| <p>You should avoid pulseIn for a quadcopter, the main reason being that pulseIn takes too long to execute.</p>
<p>pulseIn waits for a pulse to start, then waits until that pulse finishes, and then returns how long it took to finish. Standard RC signals pulse at 50-60Hz, with the "high" part of the signals being between 1 and 2 milliseconds. 60Hz is one pulse per 16 milliseconds or so. </p>
<p>What that amounts to is pulseIn taking at most 18 milliseconds, but never less that 1 millisecond to execute per channel. lets say you want to measure 4 channels (throttle, pitch, yaw, roll); the average time would be around 40 milliseconds.</p>
<p>In general 40 milliseconds isn't so long, but your quad will need to read the accelerometer and gyroscope and stabilize itself more often then that in the air. A loop that takes 40 ms is running at 25Hz, but the stabilize loop in all the quadcopter implementations I'm familiar with is run at 100Hz or higher (thats areoquad, multiWii, and ardupilot).</p>
<p>You should use interrupts to read the values, because interrupts are non blocking, and give higher quality readings. Some specialized quadcopter boards have other processors read the actual RC signals and send the result back to the main processor to cut down on the number of interrupts they have to use.</p>
<hr>
<p>FYI, The standard servo output library sends new signals at 50Hz. Those open source quadcopters use their own implementations that run at higher output frequencies, since brushless ESCs support that. There is a pull request with code to add support for different refresh intervals to the arduino servo library <a href="https://github.com/arduino/Arduino/pull/2446" rel="nofollow">here</a> that I have tested; You could try appling it as a patch to your installation if the output rate gives you trouble down the road.</p>
|
9467 | |serial|c++| | Serial communication and Arduino program in C | 2015-03-19T18:56:41.700 | <p>When I flash this simple code (using <a href="https://github.com/sudar/Arduino-Makefile" rel="nofollow">Arduino-Makefile</a>):</p>
<pre><code>#include <avr/io.h>
#include <util/delay.h>
#include <Arduino.h>
void init_io(void) {
// open serial port
Serial.begin(9600);
while (!Serial);
Serial.println("Comm-link online");
}//END: init_io
int main(void) {
init_io();
while (1) {
// send data only when you receive data:
if (Serial.available() > 0) {
// read the incoming byte:
int incomingByte = Serial.read();
// say what you got:
Serial.print("I received: ");
Serial.println(incomingByte, DEC);
} else {
// Serial.println("No serial ");
}
}//END: loop
return 0;
}//END: main
</code></pre>
<p>I only see first two chars printed in the serial output:</p>
<blockquote>
<p>~$> Co</p>
</blockquote>
<p>The input also does not work as intended - tested on two independent microcontrolers, Mega and Uno. I'm not sure what's the cause of this behaviour. Here's the Makefile:</p>
<pre><code>BOARD_TAG = uno # megaADK uno
MONITOR_PORT = /dev/ttyACM0
ARDUINO_LIBS =
include $(ARDMK_DIR)/Arduino.mk
</code></pre>
<p>It's definitely not a hardware problem, I've used serial i/o before in other projects.</p>
| <p>When using the Arduino core library, you normally do not write a
<code>main()</code> function. Instead, you write <code>setup()</code> and <code>loop()</code> and rely on
libcore's provided <code>main()</code> for calling them.</p>
<p>If you nevertheless want to provide your own <code>main()</code>, then you should
call <code>init();</code> (with no arguments) before you try to use the library.
Adding this single call makes your program work on my Uno.</p>
<p>However, since it does not seem to be officially documented, this trick
may not be safe against upgrades in the core library. Writing <code>setup()</code>
and <code>loop()</code> should be more future-proof.</p>
|
9469 | |arduino-uno|programming|arduino-leonardo|arduino-micro|teensy| | How big of a difference is there between an Arduino Uno and the rest? | 2015-03-19T19:45:31.347 | <p>Lately I've been fooling around with a project for my Microsoft Sidewinder Force Feedback Pro Joystick. I've found out that there is a project currently for it <a href="https://code.google.com/p/adapt-ffb-joy/" rel="nofollow">built for the Teensy 2.0</a>. On the page for the Teensy 2.0 there is a link for an <a href="https://code.google.com/p/sidewinder-arduino/" rel="nofollow">Arduino Library</a> for the very same project that was (I guess) converted. There isn't much documentation for it, and I don't think there is much progress being made on it anymore. However when I grab the files and try to upload it to my Arduino Uno it spits out an Unsupported device. Doing some digging around I found where it shows what devices are supported in the includes.h.. Which happen to be</p>
<pre><code>#if defined(__AVR_AT90USB162__) || defined(__AVR_AT90USB82__)
#define __AVR_AT90USBX2__
#elif defined(__AVR_ATmega16U4__) || defined(__AVR_ATmega32U4__)
#define __AVR_ATmegaXU4__
#elif defined(__AVR_AT90USB646__) || defined(__AVR_AT90USB1286__)
#define __AVR_AT90USBX6__
#else
#error "Unsupported device"
#endif
</code></pre>
<p>Which ends up being the red arduino, arduino micro, arduino leonardo, and I think a few teensys. </p>
<p>What I want to know is if you can upload this code onto a UNO. I'm not really wanting to purchase a teensy just to check if this will work or not.</p>
| <p>The code won't work as a traditional project when uploaded on an Uno, because the Uno does not talk directly to the Host, it only speaks UART.</p>
<p>But good news is that the Uno uses another atmega chip, an Atmega8u2 on the older models or Atmega16u2 on the others. That IC handles directly the USB connection with the host on behalf of the Atmega328. And that code below is actually (close enough) support for that IC:</p>
<pre><code>#elif defined(__AVR_ATmega16U4__) || defined(__AVR_ATmega32U4__)
#define __AVR_ATmegaXU4__
</code></pre>
<p>That means you should be able to upload the code (or a similar one) on that 'frontend' IC, so it acts as a HID device, and connects to the main 328 for any I/O you might need.</p>
<p>To do the upload on that other chip, you can use an ISP programmer on the 6pins header close to USB, or you can use the DFU programmation mode over USB.</p>
<p>I'm sorry for not giving external references or code, but I'm answering from my phone!</p>
<p>Edit: after a short browse over the code, it's definitely <em>possible</em> to implement that using an uno, but you'll need to split the code between the two chips: the USB interface to behave like ah HID device and the main I/O chip to talk midi, and implement comms between both.</p>
<p>Edit #2: </p>
<p>Here's a few resources that might help to work out USB and Midi using Arduino, but it looks like none is a cooked in USB on atmegaXu2 to Midi on atmega328:</p>
<ul>
<li><a href="http://unojoy.tumblr.com/" rel="nofollow noreferrer">http://unojoy.tumblr.com/</a></li>
<li><a href="http://forum.arduino.cc/index.php/topic,111.0.html" rel="nofollow noreferrer">http://forum.arduino.cc/index.php/topic,111.0.html</a></li>
<li><a href="http://hunt.net.nz/users/darran/weblog/15f92/Arduino_UNO_Big_Joystick_HID_firmware.html" rel="nofollow noreferrer">http://hunt.net.nz/users/darran/weblog/15f92/Arduino_UNO_Big_Joystick_HID_firmware.html</a></li>
<li><a href="https://stackoverflow.com/questions/16710701/joystick-usb-definition-for-use-with-arduino">https://stackoverflow.com/questions/16710701/joystick-usb-definition-for-use-with-arduino</a></li>
<li><a href="http://hackaday.com/2011/03/28/hiduino-the-only-limit-is-yourself/" rel="nofollow noreferrer">http://hackaday.com/2011/03/28/hiduino-the-only-limit-is-yourself/</a></li>
<li><a href="http://arduino.cc/en/Hacking/DFUProgramming8U2" rel="nofollow noreferrer">http://arduino.cc/en/Hacking/DFUProgramming8U2</a></li>
<li><a href="http://arduino.cc/en/tutorial/midi" rel="nofollow noreferrer">http://arduino.cc/en/tutorial/midi</a></li>
<li><a href="https://sites.google.com/site/bharatbhushankonka/home/diy-midi-over-usb-using-arduino-uno" rel="nofollow noreferrer">https://sites.google.com/site/bharatbhushankonka/home/diy-midi-over-usb-using-arduino-uno</a></li>
<li><a href="http://www.instructables.com/id/Turn-your-Arduino-Uno-into-an-USB-HID-Mididevice/" rel="nofollow noreferrer">http://www.instructables.com/id/Turn-your-Arduino-Uno-into-an-USB-HID-Mididevice/</a></li>
</ul>
<p>And if you're not at ease with AVR development, it's gonna be <strong>HARD</strong>. You'd better get a teensy2 or a leonardo where that code should compile and work with little effort.</p>
<p>HTH</p>
|
9479 | |arduino-due|analogwrite| | Arduino Due analog output has 500mV offset | 2015-03-20T22:17:38.640 | <p>I use a simple serial connection to tell the Due what to output into an analog output pin. However, the outputs are offset about 550mV (as seen on an oscilloscope) and the maximum value of 255 gives ~2.7V. What am I missing? Why can't the DAC output 0V - 3.3V mapped onto 0 - 255 values?</p>
<pre><code>int output = DAC1; // analog output pin
String inData;
void setup()
{
Serial.begin(9600);
}
void loop() {
while (Serial.available() > 0) {
char value = Serial.read();
inData += value;
if(value == '\n'){
val = inData.toInt(); // 0..255
analogWrite(output, val);
Serial.println(val);
inData = "";
}
}
}
</code></pre>
| <pre><code>int output = DAC1; // analog output pin
String inData;
int val;
void setup()
{
Serial.begin(9600);
}
void loop() {
while (Serial.available() > 0) {
char value = Serial.read();
inData += value;
if(value == '\n'){
val = inData.toInt(); // 0..255
val=constrain(val, 543, 2720);
analogWrite(output, map(val,543,2720, 0, 255));
Serial.println(val);
inData = "";
}
}
}
</code></pre>
|
9481 | |arduino-mega|pins|pwm|interrupt| | Why is my interrupt code not working? | 2015-03-21T00:09:16.153 | <h3>Background</h3>
<p>I'm trying to write code to read signals from a six-channel RC receiver on an <a href="https://www.arduino.cc/en/Main/ArduinoBoardMega2560" rel="nofollow noreferrer">Arduino Mega 2560</a>. Currently I am keeping the code to just read one channel to make things easy to troubleshoot. The problem is my shared variable is not updating, leading me to believe that my interrupt service routine is not detecting any rising edges.</p>
<p>I thought my receiver was broken, so I tested it using <a href="https://www.arduino.cc/en/Reference/AttachInterrupt" rel="nofollow noreferrer">the standard Arduino attach interrupt function</a>. It worked perfectly, so my receiver is fine.</p>
<p>I used <a href="https://www.arduino.cc/en/Serial/Print" rel="nofollow noreferrer">Serial.print()</a> to see if my volatile channel variable was updating (that is, change its value to the channel 1 flag value). It was not updating, so my <a href="https://en.wikipedia.org/wiki/Interrupt_handler" rel="nofollow noreferrer">ISR</a> must be wrong. You can find the original code in the blog post.</p>
<p>What's wrong? I'm out of ideas.</p>
<pre class="lang-cpp prettyprint-override"><code>#include <PinChangeInt.h>
//Pin assignment
#define channel1PIN 10
//Bit flags
#define Channel1FLAG 1
//Flag holder
volatile uint8_t bFLAGUPDATESHARED;
//Shared variables: Accessed by the interrupt service routine and read in 'void loop'.
volatile uint16_t unCHANNEL1SHARED;
//Start time variables: These are used to set the start time of the rising edge of
//a pulse. They are only accessed by the ISR, and thus they are unsigned integers and
//not volatiles.
uint32_t ulCHANNEL1START;
void setup()
{
Serial.begin(9600);
Serial.print("RC Channel PWM Read Interrupt Test");
//PinChangInt library function. Used to set attach interrupts.
PCintPort::attachInterrupt(channel1PIN, calcCHANNEL1, CHANGE);
}
void loop()
{
//In-loop variables to hold local copies of channel inputs.
//This is static so it retains values between call loops.
static uint16_t unCHANNEL1IN;
//The in-loop copy of the bSHAREDFLAGUPDATE volatile flag holder
static uint8_t bFLAGUPDATELOCAL;
//Check to see if any channels have received signals. If so, copy
//shared variables to local in loop variables.
if (bFLAGUPDATESHARED)
{
//Switch off interrupts when I copy shared variables to local variables
noInterrupts();
bFLAGUPDATELOCAL = bFLAGUPDATESHARED;
if (bFLAGUPDATELOCAL & Channel1FLAG)
{
unCHANNEL1IN = unCHANNEL1SHARED;
}
bFLAGUPDATESHARED = 0;
interrupts();
}
Serial.println(unCHANNEL1IN);
//Clear local update flags copy as all values have been copied to local variables
bFLAGUPDATELOCAL = 0;
}
void calcCHANNEL1()
{
if (digitalRead(channel1PIN) == HIGH)
{
//If pin goes high, start timer and set ulCHANNEL1START to timer start
ulCHANNEL1START = micros();
}
else
{
//If it is not rising, it must be falling so set shared
//variable to current time-start time
unCHANNEL1SHARED = (uint16_t)(micros() - ulCHANNEL1START);
//Tell that channel 1 has received a signal
bFLAGUPDATESHARED |= Channel1FLAG;
}
}
</code></pre>
| <p>Only <strong>some</strong> ports on the Atmega2560 support pin-change interrupts, specifically ports B, E (bit 0), J (bits 0 to 6) and K.</p>
<p>Looking at the reference schematic that means that these pins on the board are supported:</p>
<pre><code> Chip
Name Pin Pin on board
-----------------------
Port B
PB0 - 19 - D53 (SS)
PB1 - 20 - D52 (SCK)
PB2 - 21 - D51 (MOSI)
PB3 - 22 - D50 (MISO)
PB4 - 23 - D10
PB5 - 24 - D11
PB6 - 25 - D12
PB7 - 26 - D13
Port E
PE0 - 2 - D0 (RXD0)
Port J
PJ0 - 63 - D15 (RXD3)
PJ1 - 64 - D14 (TXD3)
PJ2 to PJ6 - not connected on board
Port K
PK0 - PK7 - (89 - 82) - A8 - A15
</code></pre>
<p>Thus you can see that D10 to D12, which you say works, are in that list. Other random ones would not be.</p>
<hr>
<h3>SoftwareSerial</h3>
<p>You can see confirmation on the page for <a href="https://www.arduino.cc/en/Reference/softwareSerial" rel="nofollow noreferrer">SoftwareSerial</a> where it says:</p>
<blockquote>
<p>Not all pins on the Mega and Mega 2560 support change interrupts, so only the following can be used for RX: 10, 11, 12, 13, 14, 15, 50, 51, 52, 53, A8 (62), A9 (63), A10 (64), A11 (65), A12 (66), A13 (67), A14 (68), A15 (69). </p>
</blockquote>
<p>This is because SoftwareSerial uses pin-change interrupts to detect incoming serial data, and thus the disclaimer on that page about which pins it will work with.</p>
<hr>
<h3>Atmega2560 pin-outs</h3>
<p><a href="https://i.stack.imgur.com/N3mkj.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/N3mkj.png" alt="Atmega2560 pin-outs"></a></p>
<hr>
<blockquote>
<p>PinchangeInt should work on any digital pin</p>
</blockquote>
<p>Note that the Atmega328P (as used in the Uno) has less ports, and all are available for pin-change interrupts on that board.</p>
|
9483 | |gsm| | How to communicate the Arduino board with SIM900? | 2015-03-21T02:54:14.663 | <p>I have a problem. I bought a SIM900 board, but I can not connect there with the Arduino. To send AT commands on the serial the SIM900 doesn't respond, but the LED indicating that the network is on. I've tried to change the baud rate of 9600 to 19200 in the firmware of the Arduino, but it still fails. I think I'm having a problem with the connections of the SIM900, since this board strikes me as obscure (could not find the schematic on the Internet)</p>
<p>The board I have is identical to this:
<img src="https://i.stack.imgur.com/IwIem.jpg" alt="enter image description here"></p>
<p>I'm 90% sure that I am connecting to the wrong pins. But I tried to reverse the jumpers and even some soldered pins on UART.</p>
| <p>I'll tell you what worked for me, because I didn't find the schematics of this board. But your board may work differently, so it is always good to check the datasheet and the schematic (if you have one).</p>
<h2><strong>Power</strong></h2>
<p>Be sure to use an external 5V source that can supply up to 2A without dipping significantly. </p>
<h2><strong>Code</strong></h2>
<pre><code>#include <SoftwareSerial.h>
SoftwareSerial GPRS(7, 8); //7 = TX, 8 = RX
unsigned char buffer[64]; port
int count=0;
int i = 1; //if i = 0, send SMS.
void setup(){
//delay(10000);
GPRS.begin(19200); // the GPRS baud rate
Serial.begin(19200); // the Serial port of Arduino baud rate.
Serial.print("I'm ready");
Serial.print("Hello?");
}
void loop(){
if (GPRS.available()){ // if date is comming from softwareserial port ==> data is comming from gprs shield
while(GPRS.available()){ // reading data into char array
buffer[count++]=GPRS.read(); // writing data into array
if(count == 64)break;
}
Serial.write(buffer,count); // if no data transmission ends, write buffer to hardware serial port
clearBufferArray(); // call clearBufferArray function to clear the storaged data from the array
count = 0; // set counter of while loop to zero
}
if (Serial.available()) // if data is available on hardwareserial port ==> data is comming from PC or notebook
GPRS.write(Serial.read()); // write it to the GPRS shield
if(i == 0){
GPRS.print("AT+CMGF=1\r"); //sending SMS in text mode
Serial.println("AT+CMGF=1\r");
delay(1000);
GPRS.print("AT+CMGS=\"+554988063979\"\r"); // phone number
Serial.println("AT+CMGS=\"+554988063979\"\r");
delay(1000);
GPRS.print("Test\r"); // message
Serial.println("Test\r");
delay(1000);
GPRS.write(0x1A); //send a Ctrl+Z(end of the message)
delay(1000);
Serial.println("SMS sent successfully");
i++;
}
}
void clearBufferArray(){ // function to clear buffer array
for (int i=0; i<count;i++){
buffer[i]=NULL; // clear all index of array with command NULL
}
}
</code></pre>
<h2><strong>Connection</strong></h2>
<p><img src="https://i.stack.imgur.com/PfIu8.jpg" alt="enter image description here"></p>
<h2><strong>Testing...</strong></h2>
<p>Open the serial monitor Arduino, set the baud rate in 19200 in "Both NL & CR". If not work, set to "Carriage Return". Type "AT" and wait for an OK.</p>
<p><img src="https://i.stack.imgur.com/YaamU.png" alt="enter image description here"></p>
<h2><strong>Help</strong></h2>
<p>If you need help, these links were useful to me:</p>
<ol>
<li><a href="http://www.seeedstudio.com/wiki/GPRS_Shield_V1.0" rel="nofollow noreferrer">http://www.seeedstudio.com/wiki/GPRS_Shield_V1.0</a></li>
<li><a href="http://www.seeedstudio.com/wiki/GPRS_Shield_V2.0" rel="nofollow noreferrer">http://www.seeedstudio.com/wiki/GPRS_Shield_V2.0</a></li>
<li><a href="http://www.elecfreaks.com/wiki/index.php?title=EFCom_GPRS/GSM_Shield" rel="nofollow noreferrer">http://www.elecfreaks.com/wiki/index.php?title=EFCom_GPRS/GSM_Shield</a></li>
</ol>
|
9489 | |arduino-uno|lcd| | Arduino Uno - combined LCD and keypad interfacing problem | 2015-03-21T09:10:53.343 | <p>I have a problem with the Arduino Uno. </p>
<p>I need to use a 4x3 keypad and 16x2 LCD together with an Arduino Uno. As 4x3 keypad requires 7 pins, I have defined pins 2, 3, 4, 5, 6, 7 and 8 to it. A 16x2 LCD requires 6 pins but only 5 pins remain (9, 10, 11, 12 and 13). Pins 0 and 1 are used for serial. </p>
<p>Please suggest a probable solution.</p>
| <p>Am new at this but I am working on a similar work, it is possible to use the pin 0 for your keypad, the pin is a RX pin by default making the pins(0,2,3,4,5,6,7).</p>
<p>As for the LCD I would suggest you use an i2c backpack, it is a parallel to serial converter and means you would only need to use 2 pins (SDA, SCL which would be connected to pin A4, A5)</p>
<p>Try the code below for the keypad (The code is if you have an i2c backpack)</p>
<pre><code>#include <Wire.h>
#include <Keypad.h> //keypad library
#include <LiquidCrystal_I2C.h> //library for the backpack
LiquidCrystal_I2C lcd(0x27, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE);
const byte ROWS = 4; //four rows
const byte COLS = 3; //three columns
//define the Symbols on the buttons of the keypads
char hexaKeys[COLS][ROWS] = {
{'1','2','3'},
{'4','5','6'},
{'7','8','9'},
{'*','0','#'}
};
byte rowPins[ROWS] = {0, 2, 3, 4}; //connect to the row pinouts of the keypad
byte colPins[COLS] = {5, 6, 7, 8}; //connect to the column pinouts of the keypad
//initialize an instance of class NewKeypad
Keypad customKeypad = Keypad( makeKeymap(hexaKeys), rowPins, colPins, ROWS, COLS);
void setup(){
Serial.begin(9600);
lcd.begin(16,2);
for(int i = 0; i< 3; i++)
{
lcd.backlight(); delay(250);
lcd.noBacklight(); delay(250);
}
lcd.backlight();
}
void loop(){
char customKey = customKeypad.getKey();
if (customKey){
lcd.print(customKey);
}
}
</code></pre>
|
9490 | |avr|assembly|avr-toolchain| | Storing in a global variable using inline assembly | 2015-03-21T11:27:16.910 | <p>What I'm trying to do is pretty basic: I have a global variable and I'm trying to store some value in it (specifically, the SP_H and SP_L values).</p>
<p>The variable is an array of structs and I'm trying to access one of those structs.</p>
<p>This is what I am doing:</p>
<pre><code>typedef struct_t { uint8_t sp_h, sp_l; } struct_t;
struct_t arr[MAX_STRUCTS];
void some_inline_assembly_function()
{
volatile asm(
// Determine where to store the new SP_H and SP_L register
"lds r26, ??? \n\t" // <-- How do I store the address
of arr[0].sp_h or arr[0].sp_l
in the X registers (r26,27)
"lds r27, ??? \n\t"
// This part stores the stack pointer low and high byte indirectly
using the X registers (r26,27), which is what I want.
"in r0, __SP_L__ \n\t"
"st x+, r0 \n\t"
"in r0, __SP_H__ \n\t"
"st x+, r0 \n\t"
::);
}
</code></pre>
<p>If this looks familiar, it is because it probably is. I'm trying to implement simple context switching (pushing the entire task context into the stack and retrieving another one). What I'm trying to accomplish is storing the current PC_H and PC_L to a global variable so that the "shceduler" knows where to start popping the registers and restore the context.</p>
<p>Yes, I know FreeRTOS does this. I need to know how to do this myself.</p>
<p>Thanks a bunch.</p>
| <p>The address you are looking for is a symbol known by the linker. Then
you can have the linker put the <em>value</em> of the symbol straight into your
code: no need to load from memory. In other words, you use the <code>ldi</code>
instruction to load the required address as an <em>immediate</em> value. You
should also reverse the order of the struct definition, since you are
storing SPL at the lowest address.</p>
<pre class="lang-c prettyprint-override"><code>typedef struct { uint8_t sp_l, sp_h; } struct_t;
struct_t arr[MAX_STRUCTS];
void some_inline_assembly_function()
{
asm volatile(
// Determine where to store the new SP_H and SP_L register
"ldi r26, lo8(arr) \n\t" // X is loaded with the symbol arr
"ldi r27, hi8(arr) \n\t" // which is the address of arr[0].sp_l
// Here you may want to add 2 * an array index.
// This part stores the stack pointer low and high byte indirectly
// using the X registers (r26,27), which is what I want.
"in r0, __SP_L__ \n\t"
"st x+, r0 \n\t"
"in r0, __SP_H__ \n\t"
"st x+, r0 \n\t"
::);
}
</code></pre>
<p>Notice the <code>lo8()</code> and <code>hi8()</code> assembler macros: they split the address
into low and high bytes. Actually the assembler translates them into
R_AVR_LO8_LDI and R_AVR_HI8_LDI relocations records, and the
linker does the real job.</p>
<p><strong>Edit</strong>: I think I just realized why you were thinking of using <code>lds</code>
in the first place...</p>
<p>Instead of using array indices, you may want to access the array through
a pointer (declared <code>struct_t *pointer</code>). When programming in C or C++,
a pointer identifier behaves, for most purposes, just like an array
identifier. However, at the assembly level, using a pointer involves an
extra indirection, as you have to read the contents of the pointer from
RAM. In this case you would indeed be using <code>lds</code> instructions:</p>
<pre><code>; Copy the global 'pointer' into the X pointer register.
lds r26, pointer ; low byte
lds r27, pointer+1 ; high byte
</code></pre>
<p>As a side note, if you are programming in C++, then you have to declare
<code>extern "C"</code> any identifier that you want to use both in C++ and in
assembly. Otherwise the C++ compiler will
<a href="http://en.wikipedia.org/wiki/Name_mangling" rel="nofollow">mangle its name</a> and you
would need to use the mangled name in the assembly source.</p>
|
9494 | |arduino-uno|time|millis| | How to start a block of code after a certain time? | 2015-03-21T17:24:56.890 | <p>I'm using a ATMega328P-PU on a breadboard as an arduino. How do you start a code after say 20 seconds have elapsed since startup?
Example code:-</p>
<pre><code>if(condition)
{
//Start sending morse code!
}
</code></pre>
<p>My current code uses <code>millis()</code> and fails miserably. The speaker does not get activated. I'm using the standard circuit mentioned at the <a href="http://arduino.cc/en/main/standalone" rel="nofollow">Arduino website</a>
My current code:-</p>
<pre><code>time = millis();
if(time>=20000)
txEnable=true;
val = analogRead(analogPin);
if(val!=0)
{
standby=false;
}
else
standby=true;
if(txEnable==true && standby==true)
{
if(!callsignSender->continueSending())
{
callsignSender->startSending();
}
}
</code></pre>
| <p>The following bare-minimum code will switch pin 13 to high after 20 seconds:</p>
<pre><code>void setup() {
// assuming pin 13 has a LED connected (as on most Arduino boards)
pinMode(13, OUTPUT);
digitalWrite(13, LOW); // would also work without this line
}
void loop() {
unsigned long time = millis();
if (time >= 20000) {
digitalWrite(13, HIGH); // set the LED on
}
}
</code></pre>
<p>Try if this works for you, i.e. if a LED connected to that pin will light up 20 seconds after reboot.</p>
<p>If not you will need to find the problem: Is your ATmega running at the correct speed? Is your code executed at all? Are the peripherals working?</p>
|
9514 | |current|arduino-duemilanove| | Can I measure the current (mA) of my project with just a multi meter? | 2015-03-22T20:59:21.043 | <p>I have a project and wish to choose the correct battery back for it such that it will last the required amount of time between each recharge of the battery pack. I am using an Arduino Duemilanove with various attachements and shields.</p>
<p>I can measure that the draw on the project at the point the USB connects from my PC to the Arduino board (by attaching the multimeter to the Vcc and GND solder points on my Arduino board) which reads 5V DC as expected. Is there a way I can meausre the current (without any additional equipment) ?</p>
<p>I suspect somehow using Ohms law and measuring the resistance between two points would be the answer (knowing the voltage is 5V) but I can't work it out (as in where to measure) with my lack of any electrical knowledge.</p>
| <p>A reasonable method is to place a small value resistor in series with the supply, connect a capacitor from the Arduino side of the resistor to ground and then measure the voltage drop across the resistor. </p>
<p>If you set the resistor value such that the highest current drawn drops less than about 0.1 Volts then it will have minimal effect on most circuits.<br>
For example if max current is 100 mA then as R = V/I, Rmax <= V/I = 0.1/100 ma = 0.1V/0.1A = 1 Ohm.<br>
So generally<br>
Rseries <= Vdrop_max / Imax_A (I in Amps) or
Rseries = Vdropmax x 1000 / Imax_mA (I in milliAmps) </p>
<p>Then I_ma = Vmeter x 1000 / R</p>
<p>Example:</p>
<p>Max current = 350 mA.<br>
R <= V/I = 0.1V /0.350 A = <= 0.286 Ohm.
A 0.1 Ohm - which is a readily available standard value, will probably be good.</p>
<p>Then if meter reads say 0.033 volt (33 millivolts) then<br>
ImA = V_mv / R = 33/0.1 = 330 mA.</p>
<p>A larger resistor value, giving a larger voltage drop, can be used if the circuit will tolerate the resultant lower supply voltage. </p>
<hr>
<p>Measure the drop with a meter set to 0.2 V (200 millivolts). Nit all meters have a 0.2 V range but even some reasonably cheap ones do have and it is worth having a meter with this range for various purposes. </p>
<p>Connect a capacitor from Arduino 5Vin to ground - the more uF the better. 100 uF probably OK, 1000 uF better ... . </p>
<p>This method will smooth out short current peaks and give you an average current. This aspect can be expanded on if of interest.</p>
|
9517 | |arduino-uno|serial|power|usb| | Erratic behaviour using Serial.print() when powering only from power supply | 2015-03-22T22:10:18.903 | <p>I'm using an arduino uno with a thermal printer and the following code:</p>
<pre><code>#include "Adafruit_Thermal.h"
#include "skull.h"
#include "SoftwareSerial.h"
int printer_TX_Pin = 8; // This is the yellow wire
int printer_RX_Pin = 9; // This is the green wire
Adafruit_Thermal printer(printer_RX_Pin, printer_TX_Pin);
void setupPrinter() {
printer.begin();
};
void doPrint(char* output) {
Serial.print("Will print: ");
Serial.print(output);
Serial.print("\n");
printer.println(output);
printer.feed(2);
}
void setup() {
setupPrinter();
doPrint("This is a test to see if it will print only from power supply");
}
void loop() {
}
</code></pre>
<p>That code works fine if the arduino and printer are plugged into 5v and the arduino is also plugged in to a computer with USB. Once I remove the USB cable it starts printing:</p>
<pre><code>This is a test to see if it will
This is a test to see if it will
This is a test to see if it will
This is a test to see if it will
This is a test to see if it will
</code></pre>
<p>over and over infinitely. In other programs it prints a slightly garbled first line then stops. When I remove the serial.print lines, this doesn't occur. Why would that be?</p>
| <p>It seems likely that your Arduino is repeatedly resetting, which means it's starting the program again from the beginning all the time. This can be caused by insufficient power.</p>
<p>For the standard 5v Arduino boards, the minimum recommended voltage for an external power supply is usually 7v. An on-board regulator brings it down to 5v.</p>
<p>Technically, you <em>can</em> run them directly from an external 5v supply. However, you have to ensure that it's properly regulated, and that you bypass the on-board regulator.</p>
<p>Obviously you also have to ensure your external supply is capable of sourcing sufficient current. If you're just running an Arduino and a small thermal printer then it's probably OK, but it's certainly worth checking.</p>
|
9538 | |atmega328|eclipse|avr-gcc|gcc| | Using an Arduino board to program an AVR | 2015-03-23T18:22:18.400 | <p>I think the arduino board is awesome.
Though I'm not interested in the library and IDE at all...
Is there a way, to use an AVR 328p, as you normally would, on an arduino board?</p>
<p>I like how arduino's can be programmed through serial, can get powered through serial and I often use serial as a debugging option. Making my own board (with ICSP programmer) would not be able to do this (withouth bootloader).</p>
<hr>
<p><strong>The Question</strong></p>
<p>Do I have to use all the stuff from arduino?</p>
<ul>
<li>Can I use my own compiler for an arduino board? (GNU-GCC / AVR)</li>
<li>Can I use my own IDE for an arduino board? (Eclipse / Atmel Studio)</li>
<li>Can I still program through serial then? (Does the bootloader care which compiler I used? Does Eclipse/AVR studio have the options to program through serial?)</li>
<li>Other stuff I should take in mind. (Annoying things like AVR studio not having a COM port window, though that's an easy fix.)</li>
</ul>
<p>Edit: We've programmed an AVR 328P (GNU-GCC / Eclipse / ICSP) in school, so I know it takes quite some work to get the compiler set up, working with Eclipse. You don't have to completely describe the proces :) Just to avoid someone spending hours on an answer that's easily found on the internet.
(On my search for this subject I could only find people doing the other way around, getting an 328p chip to work with arduino)</p>
| <ol>
<li>Do I have to use all the stuff from arduino?</li>
</ol>
<p>A = No!</p>
<ol start="3">
<li>Can I use my own compiler for an arduino board? (GNU-GCC / AVR)</li>
<li>Can I use my own IDE for an arduino board? (Eclipse / Atmel Studio)</li>
<li>Can I still program through serial then? (Does the bootloader care which</li>
</ol>
<p>Of Course! I use <code>Eclipse IDE</code> and I programming boards with Arduino bootloader directly in <code>C/C++</code> using avr-gcc and avrdude.</p>
<h2><strong>Configuring Eclipse</strong></h2>
<p>First, let's download a plug-in for integrating <code>AVR GCC</code> and <code>Avrdude</code> + <code>Eclipse IDE</code></p>
<p>To install the plug-in, point to the menu "Help> Install new software":</p>
<p><img src="https://i.stack.imgur.com/gPhH1.jpg" alt="enter image description here" /></p>
<p>We will set a new location to download the plugin. Click the "Add ..." and type: AVR - Eclipse and the URL: <a href="http://avr-eclipse.sourceforge.net/updatesite" rel="nofollow noreferrer">http://avr-eclipse.sourceforge.net/updatesite</a></p>
<p><img src="https://i.stack.imgur.com/Cuc1E.jpg" alt="enter image description here" /></p>
<p>Now select the plugin that appeared in the list and click "Next":</p>
<p><img src="https://i.stack.imgur.com/MTTEJ.jpg" alt="enter image description here" /></p>
<p>Next, next, "I Acept the terms...", restart...</p>
<p>Now we install the plug-in, we will set it up. Point to the menu "Window> Preferences." Click in "AVRDUDE". The following screen:</p>
<p><img src="https://i.stack.imgur.com/lQy8i.jpg" alt="enter image description here" /></p>
<p><strong>On the next screen "AVR DUDE" let's set our recorder. Click "Add" to "Programmer configuration". Search for "Arduino".</strong></p>
<p><img src="https://i.stack.imgur.com/HLsHL.jpg" alt="enter image description here" /></p>
<p>Or, if you prefer, you can program making use of avr libraries in own Arduino IDE. Try to upload the following code into an Arduino board! While a blink costs almost 1,056 bytes of memory using an Arduino Uno, the following code uses only 164 bytes and does the same thing :)</p>
<pre><code>#define F_CPU 16000000UL
#include <avr/io.h>
#include <util/delay.h>
#define set_bit(Y,bit_x) (Y|=(1<<bit_x))
#define clr_bit(Y,bit_x) (Y&=~(1<<bit_x))
#define tst_bit(Y,bit_x) (Y&(1<<bit_x))
#define cpl_bit(Y,bit_x) (Y^=(1<<bit_x))
#define LED PB5
int main( ){
DDRB = 0xFF;
while(1){
cpl_bit(PORTB,LED);
_delay_ms(200);
}
}
</code></pre>
<p>If you use Linux, you can take a <code>sudo cat/dev/ttyACM0</code> to detect what lies serial and <code>echo "string" >> /dev/ttyACM0</code> to send data.</p>
|
9544 | |motor|remote-control| | What is the best transmitter/receiver to use with an Arduino RC? | 2015-03-24T02:58:54.903 | <p>I want to customize an RC car that I have because the controller is gone. I'm going to use an Arduino with a custom motor controller but I have no idea what to use for the transmitter/receiver. I've seen some IR sensors being used but I want something that uses a frequency channel. Has anyone had experience doing this? What is the easiest way to go about accomplishing a remote controlled Arduino car? </p>
| <p><a href="http://rads.stackoverflow.com/amzn/click/B00E594ZX0" rel="nofollow">Here</a> is a link to a pair of Arduino compatible wireless transceivers. One of the listed applications in the description is "remote control systems such as RC vehicles," so I think this product would suit your project well.</p>
<p>According to the reviews / answers to questions on Amazon, the transceivers have an reliable range of just around 120 feet, so this component would be entirely appropriate in a remote-controlled build.</p>
|
9548 | |arduino-uno|power|battery|nrf24l01+| | Portable power for an UNO with a nrf24l01+ attached? | 2015-03-24T04:02:25.773 | <p>Okay so I have an UNO that has an nrf24l01+ attached. I want it to be completely wireless so free of the 5v USB power and the 12V wall plug. In this case what can I use? I do not wish to plug the power directly into the Vin as I am relatively new and afraid that it might fry the board. So I wish to plug it into the barrel jack. So I have read that using a 9v battery to power UNO is a waste of power as most of the power is translated into heat. Also, using 4 AA batteries seem to be a good solution except that I'm not sure if it has enough power for nrf24l01+ as I've read that an arduino with nrf24l01+ on batteries creates an unstable wireless node. I would like some help on what I can power the UNO with.</p>
| <p>Firstly if you only need short runs, go with the usb battery pack answer, but if you need the longest time from least batteries:</p>
<p>As has been pointed out, for best battery consumption an arduino board is not efficient due to power regulators and led lights. For best performance you want a standalone 328 chip with its BOD (brown out detector) reduced to 1.8v and then you can run it and the nrf24 chip off 2x AA batteries.</p>
<p>But all this might be a bit beyond you.</p>
<p>One thing though that will help your battery life is a PNP transistor or Mosfet on the +ve of your nrf24l01+ module triggered by a arduino io pin. as these power amplified versions dont sleep (per say, the chip does but not the PA) so it will always be consuming a large amount of power regardless of state. So just use your io pin to power it on and off for each use. </p>
<p>(that is unless you need it on always for recieving, in which case this wont help)</p>
|
9557 | |serial|arduino-mega|wires| | do two arduinos that are linked to a common 9v rail and ground still need a common negative connection for a serial tx rx connection? | 2015-03-24T15:19:28.980 | <p>so that there a 2 wires rather than 3 to connect between the two for purposes of serial communication. And the same question for 3 arduino megas on a common rail and using serial connections?</p>
| <p>All voltages are ground referenced, hence the ground is the only (supply) connection required. Remote modules can be self-powered and signals will still be discriminated as long as ground is connected.</p>
|
9558 | |arduino-nano| | Arduino Nano For Home Automation | 2015-03-24T15:20:49.483 | <p>My question is about the arduino Nano or Micro and the smallest and cheapest way to control a bigger power source. I would wire it with a socket so that I could send a command from the board and a light would turn on for example.</p>
| <p>A relay is a common way to allow a smaller power source to safely control a larger one. A relay is like a switch.</p>
<p>Here's some <a href="https://learn.adafruit.com/adafruits-raspberry-pi-lesson-13-power-control/hardware" rel="nofollow">reference material</a> about using a relay with a microcontroller. You shouldn't have much trouble finding more material now that you know what you're looking for. </p>
|
9567 | |motor|arduino-nano|robotics| | Arduino Nano Motor | 2015-03-24T21:13:29.383 | <p>If I had four of these <a href="http://www.ebay.com/itm/10pcs-Nidec-1-5V-DC-20-200mA-Micro-DC-motor-High-speed-Low-noise-Mini-dc-motor-/221718326366" rel="nofollow">motors</a> and attached them to the Arduino Nano on four separate digital pins or analog pins without transistors and a 9v power supply attached to the regular power supply input would that work? </p>
| <p>Yes, but don't expect to win any races.</p>
<p>If you use <code>analogWrite(HIGH)</code> on your digital pins (3, 5, 9, 10, and 11) your motors should receive 40 mA max at 5V (see <a href="http://arduino.cc/en/Main/arduinoBoardNano" rel="nofollow">http://arduino.cc/en/Main/arduinoBoardNano</a>). So the motors will run, just not very fast. </p>
<p>A <a href="http://bildr.org/2011/03/high-power-control-with-arduino-and-tip120/" rel="nofollow">switching transistor</a> would be a very simple addition that would allow you to achieve higher current input to the motors and get their full potential. </p>
<p>If you want to reverse the direction of the motors you'll need to investigate getting a <a href="https://www.pololu.com/product/2130" rel="nofollow">cheap motor driver board</a>.</p>
|
9581 | |wifi|wires|esp8266| | Wiring Lilypad USB + ESP8266 Serial WiFi Module | 2015-03-25T08:12:37.753 | <p>I am trying to solve the following scenario:
Lilypad USB connected to WIFI through ESP8266 Serial WiFi Module.</p>
<p><a href="http://arduino.cc/en/pmwiki.php?n=Main/ArduinoBoardLilyPadUSB" rel="nofollow">http://arduino.cc/en/pmwiki.php?n=Main/ArduinoBoardLilyPadUSB</a></p>
<p><a href="http://www.seeedstudio.com/wiki/WiFi_Serial_Transceiver_Module" rel="nofollow">http://www.seeedstudio.com/wiki/WiFi_Serial_Transceiver_Module</a></p>
<p>According to the wiki:
I should connect to TX RX pins. None of them are present as "selectable pins", because they are built in.</p>
<p>This post <a href="http://forum.arduino.cc/index.php?topic=245169.0" rel="nofollow">Using LilyPad Arduino USB with LilyPad Xbee Shield </a> talks about using SoftwareSerial something that is new to me.</p>
<p>Could anyone explain how should I proceed with the wiring and if possible a sample sketch just to connect the lilypad usb with the WIFI module to my personal WIFI.</p>
<p><strong>Edit:</strong></p>
<p>I found the following <a href="http://www.prometec.net/arduino-wifi/" rel="nofollow">tutorial</a> (spanish one but easy to follow...) where they use the Arduino UNO. I tried the example with the software serial and it worked.
I saw in that tutorial sometimes the pin RST is needed. So I tried to do the same with the lilypad USB, but still didn't work.</p>
| <p>First, upload the sketch below to your Arduino. Then, try to tie RX (pin 3) and TX (pin 2) of SoftwareSerial together. Open the Serial Monitor and send some text and see if you get it back as a response.</p>
<pre><code>#include <SoftwareSerial.h>
SoftwareSerial Serial1(3, 2);
void setup()
{ Serial.begin(9600);
Serial1.begin(9600);
}
void loop()
{
if (Serial1.available())
{ char c = Serial1.read() ;
Serial.print(c);
}
if (Serial.available())
{ char c = Serial.read();
Serial1.print(c);
}
}
</code></pre>
<p>Once you get a response, then your SoftwareSerial part is working and you can then try to connect to your ESP8266.</p>
|
9586 | |arduino-mega|sd-card|rtc| | Error while saving data in text file | 2015-03-25T12:54:07.843 | <p>I created a function that saves the timestamp in a text file, but it saves unreadable. Full of invalid characters, example: <strong>Ÿ@ O ƒº!¥ Ÿ@ O ƒº!¥ Ÿ@ O ƒº!¥ Ÿ</strong></p>
<pre><code>#include <Wire.h>
#include <SPI.h>
#include <SD.h>
#include "RTClib.h"
RTC_Millis rtc;
File txt;
const char * getCurrentTimestamp()
{
char dateBuffer[40];
DateTime now = rtc.now();
sprintf(dateBuffer,"%02u-%02u-%04u %02u:%02u:%02u", now.day(), now.month(), now.year(), now.hour(), now.minute(), now.second());
return dateBuffer;
}
void saveLog()
{
txt = SD.open("dados.txt", FILE_WRITE);
txt.print(getCurrentTimestamp());
txt.close();
}
void setup() {
pinMode(53, OUTPUT);
SD.begin(4);
Serial.begin(9600);
rtc.begin(DateTime(F(__DATE__), F(__TIME__)));
}
void loop() {
Serial.println(getCurrentTimestamp());
saveLog();
delay(1000);
}
</code></pre>
<p>My code is very simple, do not understand where I went wrong. if I copy the following code snippet for <strong>saveData()</strong> function and save the <strong>dateBuffer</strong> variable, everything works normally.</p>
<pre><code>char dateBuffer[40];
DateTime now = rtc.now();
sprintf(dateBuffer,"%02u-%02u-%04u %02u:%02u:%02u", now.day(), now.month(), now.year(), now.hour(), now.minute(), now.second());
</code></pre>
<p>how to save the timestamp correctly in the file through the function <strong>getCurrentTimestamp()</strong> ?</p>
| <p>Your function, <code>getCurrentTimestamp()</code> saves the date string in an automatic variable - it is on the function's stack frame which gets freed as soon as that function returns. Either <code>Serial.println()</code> or <code>savelog()</code> is overwriting it.</p>
<p>The proper way to do what you're trying to do is to make the buffer live for the duration of both function calls. One way is to use a global buffer. Another is to declare the buffer in <code>loop()</code> and pass it to both functions.</p>
|
9587 | |arduino-uno|timing| | How can I run two Arduinos in sync for video generation? | 2015-03-25T13:39:07.620 | <p>I was thinking about building a video circuit that uses two Arduinos (maybe more) to generate video using <code>NTSC</code> and the <code>AD725</code>. Although, VGA might be nice if possible.</p>
<p>Anyway, the idea is to use one Arduino as the background layer and the other one as the sprite layer (overlay).</p>
<p>Then, instead of masking the sprite data and having more cpu time, I was thinking of running the signals through a mux. So that when drawing background data and no sprites (per scanline) then pipe the signal to the AD725. But when there is a sprite mid-line, then the >0v signal of the sprite Arduino would cause the mux to pipe its contents through to the AD725.</p>
<p>Or, something similar.</p>
<p>I believe many arcade boards from the 80's did this. Many of them had entire "sprite boards" attached and the signals would mix. Each layer would have it's own RAM and not be aware of the other layer.</p>
<p>But to do this, I would have to keep the Arduinos sync'd perfectly.</p>
<p>So that's my question. How I can do this? </p>
<p>Oh, my Arduino of choice in the beginning would be the UNO but I have others (DUE, Teensy3.1, etc.) if that would be a better fit.</p>
<p>Thanks.</p>
| <p>Arduinos are great for many things, and I think the idea of synchronizing two or more Arduinos might have several applications.
However, if I wanted to generated VGA or NTSC video, I would look at the Parallax Propeller as another option.</p>
<p>Many people use the Parallax Propeller to produce VGA video, keeping its 8 processors working in parallel.</p>
<ul>
<li><a href="http://dangerousprototypes.com/2013/01/20/hive-retro-computer/" rel="nofollow">"Hive retro computer"</a>
"containing a total of 24 RISC processors, VGA graphics, stereo sound, ...
uses all DIP and through hole components."</li>
<li><a href="https://www.ghielectronics.com/community/forum/topic?id=13725" rel="nofollow">"Signal processing module using Parallax's propeller chip"</a>,
apparently can do "video in ... to do video-overlay then send it to video out."</li>
<li>Dangerous prototypes has a long list of projects using the Parallax Propeller.
<a href="http://dangerousprototypes.com/category/parallax-propeller/" rel="nofollow">"Dangerous Prototypes: Parallax Propeller"</a></li>
<li><a href="http://demin.ws/blog/english/2012/11/22/personal-mini-computer-on-parallax-propeller/" rel="nofollow">"Pocket Mini Computer on Parallax Propeller"</a> includes VGA output</li>
<li><a href="http://www.propellerpowered.com/forum/index.php" rel="nofollow">"Propellerpowered Forums"</a> includes many people discussing video output on the Parallax Propeller.</li>
<li>etc.</li>
</ul>
|
9592 | |datalogging| | Possibilities and limitations for onboard data acquisition | 2015-03-25T20:25:44.453 | <p>I could define myself as a "nerdy cyclist", so while my interest in Arduino is steadily growing (have not bought or used yet), my first idea for a project would be:</p>
<ol>
<li>Instrument a bicycle with some sensors (accelerometer, reed switch, etc) and an Arduino;</li>
<li>Ride long distances (that is, four hours or more, sometimes non-stop);</li>
<li>When at home, download some sort of "data file" (from SD card, I think);</li>
<li>Analyze results with Python/Matlab/whatever.</li>
</ol>
<p>So my questions:</p>
<ul>
<li>Is any model of Arduino suitable for this purpose?</li>
<li>What is the expected sample rate vs number of channels? 100Hz per channel would be excellent for my purposes, for example.</li>
<li>Can I keep incrementally saving to SD "forever" (that is, while battery and card space are available)?</li>
</ul>
| <p>Another idea -
I believe if you are making electronics you must be using some smart phone?
If I am correct why don't u utilize your smart phone with Arduino?
1) Connect sensors to Arduino
2) Use Bluetooth or WiFi shield
3) Store data locally until memory available
4) Transfer to your phone or to web via phone network every hour or 5 hours.
This will make battery consumption less and also make device Compaq. </p>
<p>Regards,
Pathik SHAH</p>
|
9604 | |bootloader|isp| | Reprogram Arduino Mega 2560 using Duemilanove? | 2015-03-24T13:40:56.000 | <p>Experiencing that Mega 2560 uploading problem. Tried updating the IDE, worked for a while but symptoms went back. Now i want to reprogram that chip.</p>
<p>I'm asking this question cuz hardware ain't free and shipping is not instant.</p>
<p>I don't have a programmer. So we already know that we can program an arduino board with another arduino board as a programmer. However i just have a Duemilanove available. Will this work? Please do not answer if you're not sure.</p>
| <p>Yes it is possible.</p>
<p>You can follow this tutorial: <a href="http://www.gammon.com.au/forum/?id=11635" rel="nofollow">http://www.gammon.com.au/forum/?id=11635</a>
The uno is basically the same as the Duemilanove</p>
|
9611 | |avr|avrdude|avr-gcc| | Use Arduino Uno to program the on-board Atmega328 in C | 2015-03-26T11:25:08.553 | <p>I have an Arduino Uno board. I have seen how it is possible to program external AVR's through the Arduino Uno board, for instance an ATtiny. But I'm starting with c for atmel µc and I just want to program Atmel328's through the Arduino hardware, and being able to use the arduino pins for outputs etc. </p>
<p>So my question is, can I use the Arduino Uno board together with avrdude and avr-gcc to program the on-board atmel328 in C? And thus being able to use the Arduino pins for output and input? </p>
| <p>You're question is not so clear.
But from what I understood you are asking if you can program the Atmega328 with c using low level instruction and by setting manually all the registers in order to use IO ports of atmega. If that's what you're asking I will suggest you to use you're arduino ide to program the Atmega using register names as shown on the official datasheet. Doing so you can start learn the internal parts of the micro and at the same time you can avoid buying an external programmer. But if really want to load you're program or hex file you have to buy an external programmer.
I hope that helped</p>
<p>PS if you are using the arduino ide and writing manually the registers remember not to set incorrectly the configuration registers because that will make you're Atmega useless and you will need to buy an external programmer.</p>
<p>Edit:
For better understanding you can refer to this link.
<a href="https://balau82.wordpress.com/2011/03/29/programming-arduino-uno-in-pure-c/" rel="nofollow">Programming arduino in c</a></p>
|
9626 | |rfid| | Linkit One- Connect rc522 rfid with linkit one | 2015-03-27T02:50:25.500 | <p>Linkit One is a board based in Arduino by mediatek.
I am trying to connect a rfid reader with it <a href="http://www.ebay.com/itm/Mifare-RC522-Card-Read-Antenna-RF-Module-RFID-Reader-IC-Card-Proximity-Module-/261268585155?pt=LH_DefaultDomain_0&hash=item3cd4d23ac3" rel="nofollow noreferrer">link</a>
I am trying from past 3 days to get it working, checked my code wiring but nothing seems to get it working.
The reader is perfectly working because i tested it on raspberryPi and it worked flawlessly.
In my linkit board i am able to detect the reader but card is not getting scanned.
I am using this library <a href="https://github.com/miguelbalboa/rfid" rel="nofollow noreferrer">GitHub</a>
and my code is fairly simple one </p>
<pre><code>#include <SPI.h>
#include <MFRC522.h>
#define RST_PIN 9 //
#define SS_PIN 10 //
MFRC522 mfrc522(SS_PIN, RST_PIN); // Create MFRC522 instance
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
ShowReaderDetails(); // Show details of PCD - MFRC522 Card Reader details
Serial.println(F("Scan PICC to see UID, type, and data blocks..."));
}
void loop() {
// Look for new cards
if ( ! mfrc522.PICC_IsNewCardPresent()) {
return;
}
// Select one of the cards
if ( ! mfrc522.PICC_ReadCardSerial()) {
return;
}
// Dump debug info about the card; PICC_HaltA() is automatically called
mfrc522.PICC_DumpToSerial(&(mfrc522.uid));
}
void ShowReaderDetails() {
// Get the MFRC522 software version
byte v = mfrc522.PCD_ReadRegister(mfrc522.VersionReg);
Serial.print(F("MFRC522 Software Version: 0x"));
Serial.print(v, HEX);
if (v == 0x91)
Serial.print(F(" = v1.0"));
else if (v == 0x92)
Serial.print(F(" = v2.0"));
else
Serial.print(F(" (unknown)"));
Serial.println("");
// When 0x00 or 0xFF is returned, communication probably failed
if ((v == 0x00) || (v == 0xFF)) {
Serial.println(F("WARNING: Communication failure, is the MFRC522 properly connected?"));
}
}
</code></pre>
<p>This program in theory should detet reader and when card is scanned should display the UID. </p>
<p>I am getting msg that my card is v2, so its detecting the reader but not reading the card.
<img src="https://i.stack.imgur.com/CUH1h.png" alt="enter image description here"></p>
| <p>This link worked for me:</p>
<p><a href="http://www.grantgibson.co.uk/blog/wp-content/uploads/2012/04/ggrfid_en_ino.txt" rel="nofollow">http://www.grantgibson.co.uk/blog/wp-content/uploads/2012/04/ggrfid_en_ino.txt</a></p>
<p>Found it in a forum:</p>
<blockquote>
<p>Please have a look at this ino file
<a href="http://www.grantgibson.co.uk/blog/wp-content/uploads/2012/04/ggrfid_en_ino.txt" rel="nofollow">http://www.grantgibson.co.uk/blog/wp-content/uploads/2012/04/ggrfid_en_ino.txt</a>
this ino file works with my reader but this rc522 library does not
<a href="https://github.com/miguelbalboa/rfid" rel="nofollow">https://github.com/miguelbalboa/rfid</a> I want to know the difference as
i was not able to spot any, one works and another does not. </p>
<p>Please let me know if there is any editing to be done so to get
<a href="https://github.com/miguelbalboa/rfid" rel="nofollow">https://github.com/miguelbalboa/rfid</a> this working</p>
</blockquote>
|
9627 | |arduino-uno|programming|python| | Send multiple int values from Python to Arduino using pySerial | 2015-03-27T05:16:30.840 | <p>I'm trying to send 3 ints in the range of 0-180 from Python to the Arduino Uno device using pySerial (py3K). I have managed to send 1 int by using python's struct lib (not sure if it's the best or fastest way but it works).</p>
<p>However I'm failing to send more than 1 and every example online seems to stop at 1.</p>
<p>Here's the simplified code. The task is to send servo0-servo4 to the Arduino and apply those values to the corresponding servos.</p>
<p>Python Code</p>
<pre class="lang-python prettyprint-override"><code>import serial
import struct
import time
bge.arduino = serial.Serial('/dev/ttyACM0', 9600)
# let it initialize
time.sleep(2)
# send the first int in binary format
bge.arduino.write(struct.pack('>B', 45))
</code></pre>
<p>Arduino code</p>
<pre class="lang-C++ prettyprint-override"><code>#include <Servo.h>
Servo servo0;
Servo servo1;
Servo servo2;
void setup(){
Serial.begin(9600);
servo0.attach(3);
servo1.attach(5);
servo2.attach(6);
}
void loop(){
if(Serial.available()){
int message = Serial.read();
// control the servo
servo0.write(message);
}
}
</code></pre>
| <pre><code>void loop(){
if(Serial.available() >= 3){
// fill array
for (int i = 0; i < 3; i++){
incoming[i] = Serial.read();
}
// use the values
servo0.write(incoming[0]);
servo1.write(incoming[1]);
servo2.write(incoming[2]);
}
}
</code></pre>
|
9653 | |bootloader|avrdude| | Problem Bootloading AVR328P-PU | 2015-03-28T12:12:28.227 | <p>I executed the following steps in order to burn a bootloader into an AVR328P-PU chip I acquired on ebay.</p>
<ol>
<li><p>I have set up AVR328P-PU on a breadboard as described here: <a href="http://arduino.cc/en/main/standalone" rel="nofollow noreferrer">http://arduino.cc/en/main/standalone</a></p></li>
<li><p>I have uploaded the ArduinoISP sketch into Arduion Uno.</p></li>
<li><p>Connected the wires in a way described here <a href="http://arduino.cc/en/Tutorial/ArduinoToBreadboard" rel="nofollow noreferrer">http://arduino.cc/en/Tutorial/ArduinoToBreadboard</a> ( the setup with external clock)</p></li>
<li><p>Chose "Tools -> Programmer -> Arduion as ISP" in the IDE.</p></li>
<li><p>Chose "Burn Bootloader" from the IDE.</p></li>
<li><p>Got and error <code>avrdude: Yikes! Invalid device signature.</code>, noticed that I connected the wires in the wrong order.</p></li>
<li><p>Fixed the wired, but still got the error:</p></li>
</ol>
<p>avrdude: Version 6.0.1</p>
<pre><code> System wide configuration file is "C:\Program Files\Arduino/hardware/tools/avr/etc/avrdude.conf"
Using Port : COM3
Using Programmer : stk500v1
Overriding Baud Rate : 19200
AVR Part : ATmega328P
Chip Erase delay : 9000 us
PAGEL : PD7
BS2 : PC2
RESET disposition : dedicated
RETRY pulse : SCK
serial program mode : yes
parallel program mode : yes
Timeout : 200
StabDelay : 100
CmdexeDelay : 25
SyncLoops : 32
ByteDelay : 0
PollIndex : 3
PollValue : 0x53
Memory Detail :
Block Poll Page Polled
Memory Type Mode Delay Size Indx Paged Size Size #Pages MinW MaxW ReadBack
----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ----- ---------
eeprom 65 20 4 0 no 1024 4 0 3600 3600 0xff 0xff
flash 65 6 128 0 yes 32768 128 256 4500 4500 0xff 0xff
lfuse 0 0 0 0 no 1 0 0 4500 4500 0x00 0x00
hfuse 0 0 0 0 no 1 0 0 4500 4500 0x00 0x00
efuse 0 0 0 0 no 1 0 0 4500 4500 0x00 0x00
lock 0 0 0 0 no 1 0 0 4500 4500 0x00 0x00
calibration 0 0 0 0 no 1 0 0 0 0 0x00 0x00
signature 0 0 0 0 no 3 0 0 0 0 0x00 0x00
Programmer Type : STK500
Description : Atmel STK500 Version 1.x firmware
Hardware Version: 2
Firmware Version: 1.18
Topcard : Unknown
Vtarget : 0.0 V
Varef : 0.0 V
Oscillator : Off
SCK period : 0.1 us
avrdude: AVR device initialized and ready to accept instructions
Reading | ################################################## | 100% 0.06s
avrdude: Device signature = 0x000000 (retrying)
Reading | ################################################## | 100% 0.05s
avrdude: Device signature = 0x000000 (retrying)
Error while burning bootloader.
Reading | ################################################## | 100% 0.07s
avrdude: Device signature = 0x000000
avrdude: Yikes! Invalid device signature.
Double check connections and try again, or use -F to override
this check.
avrdude done. Thank you.
</code></pre>
<p><img src="https://i.stack.imgur.com/2hTrr.jpg" alt="Breadboard + Arduino"></p>
<p><img src="https://i.stack.imgur.com/ReuMi.jpg" alt="Breadboard Close-Up"></p>
<h1>My questions</h1>
<ol>
<li><p>I understand that this can be caused by poor breadboard quality. How can I test this hypothesis before buying new breadboard?</p></li>
<li><p>Could the wrong wiring from step 5 ruin the chip?</p></li>
</ol>
| <p>I had this exact same problem. It turned out that my atmega328p had the wrong fuses. I am not sure how to solve the problem using the default ardiuino ide, however I was able to plug my ArduinoISP into a linux machine (just plug in the usb) and correctly profram the fuses on a slave atmega328p to solve the problem:</p>
<p>The guide here gets you started, however it missing some of the fuses:
<a href="http://heliosoph.mit-links.info/arduinoisp-reading-writing-fuses-atmega328p/" rel="nofollow">http://heliosoph.mit-links.info/arduinoisp-reading-writing-fuses-atmega328p/</a></p>
<p>The full command to set the default fuses is something like this:</p>
<pre><code>avrdude -P /dev/ttyACM0 -b 19200 -c arduino -p m328p -U lfuse:w:0xFF:m -U hfuse:w:0xDE:m -U efuse:w:0x05:m
</code></pre>
|
9655 | |serial| | How can I execute a shell command? | 2015-03-28T15:01:17.223 | <p><a href="http://forum.arduino.cc/index.php?topic=38627.0" rel="nofollow">This page</a> says to run a shell command I need a "proxy code" running on my computer (Linux Ubuntu). What do they mean by this, and how should I make one?</p>
| <p>I'm not familiar with the term <em>proxy code,</em> but I'm assuming that it's a piece of code on your computer that acts as a man in the middle.</p>
<p>You cannot directly use Arduino to run a shell command, so you'll need to create a program on your computer that listens to <strong><a href="http://arduino.cc/en/reference/serial" rel="nofollow noreferrer">serial</a></strong> and then executes a command.</p>
<p>For the "proxy code" Python would be a good choice because of the <strong><a href="http://pyserial.sourceforge.net/" rel="nofollow noreferrer">pySerial library</a></strong> that plays nicely with Arduino. It seems <a href="https://stackoverflow.com/questions/89228/calling-an-external-command-in-python">fairly easy to execute a shell command with Python</a>.</p>
<p>As per the Arduino code, something like this would work good:</p>
<pre><code>setup() {
Serial.begin(9600);
}
loop() {
if(state == true) {
Serial.print('A');
}
}
</code></pre>
|
9660 | |arduino-uno| | Arduino UNO capacitive sensor not working | 2015-03-28T17:44:33.037 | <p>This is a visualization of my Arduino connections: </p>
<p><img src="https://i.stack.imgur.com/FMI00.png" alt="enter image description here"></p>
<p>I wish to read the data using the <a href="http://playground.arduino.cc/Main/CapacitiveSensor?from=Main.CapSense" rel="nofollow noreferrer">Capacitive sensor Library</a>. iv'e tried the following code but variables <code>total1</code>, <code>total2</code>, <code>total3</code> always have the value <code>0</code> and i don't know what is wrong.</p>
<p><strong>My code:</strong></p>
<pre><code>// Import the CapacitiveSensor Library.
#include <CapacitiveSensor.h>
// Name the pin as led.
#define speaker 11
// Set the Send Pin & Receive Pin.
CapacitiveSensor cs_2_3 = CapacitiveSensor(2,3); // 10M resistor between pins 4 & 2, pin 2 is sensor pin, add a wire and or foil if desired
CapacitiveSensor cs_2_4 = CapacitiveSensor(2,4); // 10M resistor between pins 4 & 6, pin 6 is sensor pin, add a wire and or foil
CapacitiveSensor cs_2_5 = CapacitiveSensor(2,5); // 10M resistor between pins 4 & 8, pin 8 is sensor pin, add a wire and or foil
CapacitiveSensor cs_2_6 = CapacitiveSensor(2,6); // 10M resistor between pins 4 & 8, pin 8 is sensor pin, add a wire and or foil
CapacitiveSensor cs_2_7 = CapacitiveSensor(2,7); // 10M resistor between pins 4 & 8, pin 8 is sensor pin, add a wire and or foil
CapacitiveSensor cs_2_8 = CapacitiveSensor(2,8); // 10M resistor between pins 4 & 8, pin 8 is sensor pin, add a wire and or foil
CapacitiveSensor cs_2_9 = CapacitiveSensor(2,9); // 10M resistor between pins 4 & 8, pin 8 is sensor pin, add a wire and or foil
void setup()
{
cs_2_3.set_CS_AutocaL_Millis(0xFFFFFFFF); // turn off autocalibrate on channel 1 - just as an example
// Arduino start communicate with computer.
Serial.begin(9600);
}
void loop()
{
// Set a timer.
long start = millis();
// Set the sensitivity of the sensors.
long total1 = cs_2_3.capacitiveSensor(60);
long total2 = cs_2_4.capacitiveSensor(60);
long total3 = cs_2_5.capacitiveSensor(60);
/* long total4 = cs_2_6.capacitiveSensor(60);
long total5 = cs_2_7.capacitiveSensor(60);
long total6 = cs_2_8.capacitiveSensor(60);
long total7 = cs_2_9.capacitiveSensor(60);*/
Serial.print(millis() - start); // check on performance in milliseconds
Serial.print("\t"); // tab character for debug windown spacing
Serial.print(total1); // print sensor output 1
Serial.print("\t"); // Leave some space before print the next output
Serial.print(total2); // print sensor output 2
Serial.print("\t"); // Leave some space before print the next output
Serial.print(total3); // print sensor output 3
Serial.print("\t"); // Leave some space before print the next output
Serial.print("\n");
}
</code></pre>
| <p>As found on the <a href="http://playground.arduino.cc/Main/CapacitiveSensor" rel="nofollow">Capacitative Sensor Library page</a> (emphasis added):</p>
<blockquote>
<ul>
<li><strong>Use a 1 megohm resistor (or less maybe) for absolute touch to activate.</strong></li>
<li>With a 10 megohm resistor the sensor will start to respond 4-6 inches away.</li>
<li>With a 40 megohm resistor the sensor will start to respond 12-24 inches away (dependent on the foil size). Common resistor sizes usually end at 10 megohm so you may have to solder four 10 megohm resistors end to end.</li>
<li><strong>One tradeoff with larger resistors is that the sensor's increased sensitivity means that it is slower. Also if the sensor is exposed metal, it is possible that the send pin will never be able to force a change in the receive (sensor) pin, and the sensor will timeout.</strong></li>
<li>Also experiment with small capacitors (100 pF - .01 uF) to ground, on the sense pin. They improve stability of the sensor.</li>
</ul>
</blockquote>
<p>The two emboldened points suggest that for a touch-piano, it would likely be advantageous to use a lower value resistor such as 1MΩ. Because the sensitivity increases as the resistor value increases, you want to use the <em>lowest possible</em> resistor value to reduce jitter & interference among your signal wires.</p>
<p><hr>
Also, later on the page:</p>
<blockquote>
<p>The grounding of the Arduino board is very important in capacitive sensing. The board needs to have some connection to ground, even if this is not a low-impedance path such as a wire attached to a water pipe.</p>
</blockquote>
<p>Ensure the Arduino is not run from a battery or unplugged laptop. For capacitative sensing to work, a stable ground connection is needed (via a DC plugpack or USB wall-wart is fine).</p>
<p>As a general note, try testing with only one capacitative connection first, then when that works, re-add the others.</p>
|
9663 | |arduino-uno|bluetooth|keyboard| | How can I use a BlueSMIRF Silver (RN-42) as a HID Keyboard (on IOS)? | 2015-03-28T19:01:01.477 | <p>I've got a BlueSMIRF Silver (RN-42) Bluetooth module.
I am trying to create a basic keyboard I can play with on an iPad Air.</p>
<p>At the moment barely manage to get the module to pair with OSX
but only through using Bluetooth Setup Assistant and using "<strong>Passcode Options...use a specific code</strong>". </p>
<p>With this option, the module pairs, but the connection resets about every 5 seconds. </p>
<p>On iPad it tries to use a generate number really fast and fails straight away, being unable to connect.</p>
<p>I noticed there is a BlueSMIRF HID version, but from what I can tell, the hardware is the same,
just the firmware is different. I've gone through the whole <a href="https://dlnmh9ip6v2uc.cloudfront.net/assets/1/e/e/5/d/5217b297757b7fd3748b4567.pdf" rel="nofollow">Bluetooth Data Module Command Reference & Advanced Information User’s Guide</a>(pdf link) manual and from what I can gather,
even though I have Silver firmware burned onto my module, I should be able to set and use the HID profile
(from the default SPP):</p>
<blockquote>
<p>Roving Networks modules shipped with firmware version 6.11 and higher
support the HID profile. You do not need special firmware if your
module is running firmware 6.11 or higher.</p>
</blockquote>
<p>and my module reports version as:</p>
<pre><code>Ver 6.15 04/26/2013
(c) Roving Networks
</code></pre>
<p>I've also gone through the <a href="http://dlnmh9ip6v2uc.cloudfront.net/datasheets/Wireless/Bluetooth/RN-HID-User%20Guide-1.1r.pdf" rel="nofollow">Bluetooth HID Profile</a>(pdf link) guide from Roving Networks, but the same information is present in Chapter 5 of the advanced user's guide mentioned above.</p>
<p>I've setup the following settings (with commands used):</p>
<ul>
<li>HID Profile (<code>S~,6</code>) </li>
<li>Device discovery and pairing is set to automatic, without using GPIO6(<code>SM,6</code>) </li>
<li>HID Flag is set to Keyboard (<code>SH,0000</code>) </li>
<li>Authentication is set to open (<code>SA,0</code>)</li>
</ul>
<p>I've also tried the inquiry scan(<code>SI,0800</code>) and page scan(<code>SJ,0800</code>) windows to maximum
in the hope it would increase the odds of successful pairing and made sure I rebooted the module and checked the settings again.</p>
<p>I have used the same module with the SPP profile just fine, but I'm still fairly new to Bluetooth
and this is the first time I try to use the HID profile.</p>
<p><strong>How can I use the BlueSMIRF Silver as a basic Bluetooth Keyboard for an iPad Air ?</strong></p>
| <p>I know I am late to the party but for others searching this topic:</p>
<p>"S~,6" command does work for switching to HID profile but it requires the reboot command "R,1" otherwise it won't take.</p>
<p>I send these commands from the microcontroller to RN42 whilst the RN42 is in command mode, just to be clear.</p>
|
9666 | |arduino-uno|serial|programming| | How to avoid blocking while loop reading Serial? | 2015-03-28T21:52:46.310 | <p>I am currently playing with a MindWave Mobile headset. I am parsing bluetooth data received from a connected BlueSMIRF Silver.
The code I started from is a <a href="http://developer.neurosky.com/docs/doku.php?id=mindwave_mobile_and_arduino" rel="nofollow">sample from the MindWave wiki</a> and it works using hardware Serial.
For reference here is the original code:</p>
<pre><code>////////////////////////////////////////////////////////////////////////
// Arduino Bluetooth Interface with Mindwave
//
// This is example code provided by NeuroSky, Inc. and is provided
// license free.
////////////////////////////////////////////////////////////////////////
#define LED 13
#define BAUDRATE 57600
#define DEBUGOUTPUT 1
#define GREENLED1 3
#define GREENLED2 4
#define GREENLED3 5
#define YELLOWLED1 6
#define YELLOWLED2 7
#define YELLOWLED3 8
#define YELLOWLED4 9
#define REDLED1 10
#define REDLED2 11
#define REDLED3 12
#define powercontrol 10
// checksum variables
byte generatedChecksum = 0;
byte checksum = 0;
int payloadLength = 0;
byte payloadData[64] = {
0};
byte poorQuality = 0;
byte attention = 0;
byte meditation = 0;
// system variables
long lastReceivedPacket = 0;
boolean bigPacket = false;
//////////////////////////
// Microprocessor Setup //
//////////////////////////
void setup() {
pinMode(GREENLED1, OUTPUT);
pinMode(GREENLED2, OUTPUT);
pinMode(GREENLED3, OUTPUT);
pinMode(YELLOWLED1, OUTPUT);
pinMode(YELLOWLED2, OUTPUT);
pinMode(YELLOWLED3, OUTPUT);
pinMode(YELLOWLED4, OUTPUT);
pinMode(REDLED1, OUTPUT);
pinMode(REDLED2, OUTPUT);
pinMode(REDLED3, OUTPUT);
pinMode(LED, OUTPUT);
Serial.begin(BAUDRATE); // USB
}
////////////////////////////////
// Read data from Serial UART //
////////////////////////////////
byte ReadOneByte() {
int ByteRead;
while(!Serial.available());
ByteRead = Serial.read();
#if DEBUGOUTPUT
Serial.print((char)ByteRead); // echo the same byte out the USB serial (for debug purposes)
#endif
return ByteRead;
}
/////////////
//MAIN LOOP//
/////////////
void loop() {
// Look for sync bytes
if(ReadOneByte() == 170) {
if(ReadOneByte() == 170) {
payloadLength = ReadOneByte();
if(payloadLength > 169) //Payload length can not be greater than 169
return;
generatedChecksum = 0;
for(int i = 0; i < payloadLength; i++) {
payloadData[i] = ReadOneByte(); //Read payload into memory
generatedChecksum += payloadData[i];
}
checksum = ReadOneByte(); //Read checksum byte from stream
generatedChecksum = 255 - generatedChecksum; //Take one's compliment of generated checksum
if(checksum == generatedChecksum) {
poorQuality = 200;
attention = 0;
meditation = 0;
for(int i = 0; i < payloadLength; i++) { // Parse the payload
switch (payloadData[i]) {
case 2:
i++;
poorQuality = payloadData[i];
bigPacket = true;
break;
case 4:
i++;
attention = payloadData[i];
break;
case 5:
i++;
meditation = payloadData[i];
break;
case 0x80:
i = i + 3;
break;
case 0x83:
i = i + 25;
break;
default:
break;
} // switch
} // for loop
#if !DEBUGOUTPUT
// *** Add your code here ***
if(bigPacket) {
if(poorQuality == 0)
digitalWrite(LED, HIGH);
else
digitalWrite(LED, LOW);
Serial.print("PoorQuality: ");
Serial.print(poorQuality, DEC);
Serial.print(" Attention: ");
Serial.print(attention, DEC);
Serial.print(" Time since last packet: ");
Serial.print(millis() - lastReceivedPacket, DEC);
lastReceivedPacket = millis();
Serial.print("\n");
}
#endif
bigPacket = false;
}
else {
// Checksum Error
} // end if else for checksum
} // end if read 0xAA byte
} // end if read 0xAA byte
}
</code></pre>
<p>One problem I have is the blocking while loop in the ReadOneByte function:</p>
<pre><code>byte ReadOneByte() {
int ByteRead;
while(!Serial.available());
ByteRead = Serial.read();
#if DEBUGOUTPUT
Serial.print((char)ByteRead); // echo the same byte out the USB serial (for debug purposes)
#endif
return ByteRead;
}
</code></pre>
<p>I am trying to avoid this so I started drafting a basic state machine approach:</p>
<pre><code>#define BAUDRATE 57600
// checksum variables
byte generatedChecksum = 0;
byte checksum = 0;
int payloadLength = 0;
byte payloadData[169] = {0};
byte poorQuality = 0;
byte attention = 0;
byte meditation = 0;
// system variables
long lastReceivedPacket = 0;
boolean bigPacket = false;
int payloadIndex;
int state = 0;
const int STATE_WAIT_FOR_FIRST_A = 0;
const int STATE_WAIT_FOR_SECOND_A = 1;
const int STATE_WAIT_FOR_PAYLOAD_LENGTH = 2;
const int STATE_WAIT_FOR_PAYLOAD = 3;
const int STATE_WAIT_FOR_CHECKSUM = 4;
const String stateNames[5] = {"waiting for first A","waiting for second A","waiting for payload length","accumulating payload","waiting for checksum"};
void setup() {
Serial.begin(BAUDRATE); // USB
}
void loop() {}
void parsePayload(){
poorQuality = 200;
attention = 0;
meditation = 0;
for(int i = 0; i < payloadLength; i++) { // Parse the payload
switch (payloadData[i]) {
case 2:
i++;
poorQuality = payloadData[i];
bigPacket = true;
break;
case 4:
i++;
attention = payloadData[i];
break;
case 5:
i++;
meditation = payloadData[i];
break;
case 0x80:
i = i + 3;
break;
case 0x83:
i = i + 25;
break;
default:
break;
} // switch
} // for loop
Serial.print("bigPacket:");
Serial.println(bigPacket);
if(bigPacket) {
Serial.print("PoorQuality: ");
Serial.print(poorQuality, DEC);
Serial.print(" Attention: ");
Serial.print(attention, DEC);
Serial.print(" Time since last packet: ");
Serial.print(millis() - lastReceivedPacket, DEC);
lastReceivedPacket = millis();
Serial.print("\n");
}
bigPacket = false;
}
void printState(){
Serial.print("state:");
Serial.println(stateNames[state]);
}
void serialEvent(){
if(Serial.available() > 0){
switch(state){
case STATE_WAIT_FOR_FIRST_A:
printState();
if(Serial.read() == 170) state = STATE_WAIT_FOR_SECOND_A;
break;
case STATE_WAIT_FOR_SECOND_A:
printState();
if(Serial.read() == 170) state = STATE_WAIT_FOR_PAYLOAD_LENGTH;
break;
case STATE_WAIT_FOR_PAYLOAD_LENGTH:
printState();
payloadLength = Serial.read();
Serial.print("payloadLength:");Serial.println(payloadLength);
if(payloadLength > 169){
Serial.println(payloadLength > 169);
state = STATE_WAIT_FOR_FIRST_A;
return;
}
generatedChecksum = payloadIndex = 0;
state = STATE_WAIT_FOR_PAYLOAD;
break;
case STATE_WAIT_FOR_PAYLOAD:
printState();
if(payloadIndex < payloadLength){
payloadData[payloadIndex] = Serial.read();
generatedChecksum += payloadData[payloadIndex];
Serial.print("payloadData[");Serial.print(payloadIndex);Serial.print(" of ");Serial.print(payloadLength);Serial.print("]: ");
Serial.println(payloadData[payloadIndex]);
}else{
state = STATE_WAIT_FOR_CHECKSUM;
}
break;
case STATE_WAIT_FOR_CHECKSUM:
printState();
checksum = Serial.read();
generatedChecksum = 255 - generatedChecksum;
if(checksum == generatedChecksum) {
Serial.println("checksum MATCH! parsing payload");
parsePayload();
state = STATE_WAIT_FOR_FIRST_A;
}else{
Serial.println("checksum FAIL!");
state = STATE_WAIT_FOR_FIRST_A;
}
break;
}
}
}
</code></pre>
<p>As far as I can understand from the <a href="http://arduino.cc/en/Reference/SerialEvent" rel="nofollow">serialEvent() reference</a> this function would be called only when a new byte is available. I've also added a condition to check if <code>Serial.available() > 0</code>.</p>
<p>I can see the messages I expect when parsing the data, but only small packets(usually 4 bytes long) end up having a correct checksum and never receive a payload with the useful EEG data I'm looking for. </p>
<p>How can I check that my approach is correct or not/ I'm not loosing bytes using <code>serialEvent()</code> instead of the blocking <code>while(!Serial.available())</code> ?
If so, how can I rewrite the while loop in a non blocking way ?</p>
<p>I've not super experienced with Arduino, but I started reading on interrupts. Would a <code>USART_RX</code> interrupt help at all ? (or would it do the same as serialEvent -> trigger when a new byte is available?)</p>
<p><strong>Update!</strong>
Using Wirewrap's suggestion to use read() which returns -1 if there is no data, I've used <a href="http://file://localhost/Applications/Arduino.app/Contents/Resources/Java/reference/Serial_Peek.html" rel="nofollow">peek()</a> which does almost the same, except it doesn't remove the character peeked at from the buffer.
For reference here is the code used:</p>
<pre><code>#define BAUDRATE 57600
#define DEBUGOUTPUT 1
// checksum variables
byte generatedChecksum = 0;
byte checksum = 0;
int payloadLength = 0;
int payloadIndex;
byte payloadData[169] = {0};
byte poorQuality = 0;
byte attention = 0;
byte meditation = 0;
// system variables
long lastReceivedPacket = 0;
boolean bigPacket = false;
int state = 0;
const int STATE_WAIT_FOR_FIRST_A = 0;
const int STATE_WAIT_FOR_SECOND_A = 1;
const int STATE_WAIT_FOR_PAYLOAD_LENGTH = 2;
const int STATE_WAIT_FOR_PAYLOAD = 3;
const int STATE_WAIT_FOR_CHECKSUM = 4;
void setup() {
Serial.begin(BAUDRATE); // USB
}
void loop() {}
void parsePayload(){
poorQuality = 200;
attention = 0;
meditation = 0;
for(int i = 0; i < payloadLength; i++) { // Parse the payload
switch (payloadData[i]) {
case 2:
i++;
poorQuality = payloadData[i];
bigPacket = true;
break;
case 4:
i++;
attention = payloadData[i];
break;
case 5:
i++;
meditation = payloadData[i];
break;
case 0x80:
i = i + 3;
break;
case 0x83:
i = i + 25;
break;
default:
break;
} // switch
} // for loop
if(bigPacket) {
Serial.print("PoorQuality: ");
Serial.print(poorQuality, DEC);
Serial.print(" Attention: ");
Serial.print(attention, DEC);
Serial.print(" Time since last packet: ");
Serial.print(millis() - lastReceivedPacket, DEC);
lastReceivedPacket = millis();
Serial.print("\n");
}
bigPacket = false;
}
void serialEvent(){
if(Serial.peek() >= 0){
switch(state){
case STATE_WAIT_FOR_FIRST_A:
if(Serial.read() == 170) state = STATE_WAIT_FOR_SECOND_A;
break;
case STATE_WAIT_FOR_SECOND_A:
if(Serial.read() == 170) state = STATE_WAIT_FOR_PAYLOAD_LENGTH;
break;
case STATE_WAIT_FOR_PAYLOAD_LENGTH:
payloadLength = Serial.read();
if(payloadLength > 169){
state = STATE_WAIT_FOR_FIRST_A;
return;
}
generatedChecksum = payloadIndex = 0;
state = STATE_WAIT_FOR_PAYLOAD;
break;
case STATE_WAIT_FOR_PAYLOAD:
if(payloadIndex < payloadLength){
payloadData[payloadIndex] = Serial.read();
generatedChecksum += payloadData[payloadIndex];
payloadIndex++;
}else{
state = STATE_WAIT_FOR_CHECKSUM;
}
break;
case STATE_WAIT_FOR_CHECKSUM:
checksum = Serial.read();
generatedChecksum = 255 - generatedChecksum;
if(checksum == generatedChecksum) {
parsePayload();
state = STATE_WAIT_FOR_FIRST_A;
}else{
state = STATE_WAIT_FOR_FIRST_A;
}
break;
}
}
}
</code></pre>
| <p>Nick Gammon, a moderator on the official Arduino site and a very active member of the Arduino community on Stackoverflow, has done a very nice post on <a href="http://www.gammon.com.au/serial" rel="nofollow">reading serial without blocking</a>. I've posted the relevant code.
/*
Example of processing incoming serial data without blocking.</p>
<pre><code>Author: Nick Gammon
Date: 13 November 2011.
Modified: 31 August 2013.
Released for public use.
*/
// how much serial data we expect before a newline
const unsigned int MAX_INPUT = 50;
void setup (){
Serial.begin (115200);
} // end of setup
// here to process incoming serial data after a terminator received
void process_data (const char * data)
{
// for now just display it
// (but you could compare it to some value, convert to an integer, etc.)
Serial.println (data);
} // end of process_data
void processIncomingByte (const byte inByte)
{
static char input_line [MAX_INPUT];
static unsigned int input_pos = 0;
switch (inByte)
{
case '\n': // end of text
input_line [input_pos] = 0; // terminating null byte
// terminator reached! process input_line here ...
process_data (input_line);
// reset buffer for next time
input_pos = 0;
break;
case '\r': // discard carriage return
break;
default:
// keep adding if not full ... allow for terminating null byte
if (input_pos < (MAX_INPUT - 1))
input_line [input_pos++] = inByte;
break;
} // end of switch
} // end of processIncomingByte
void loop()
{
// if serial data available, process it
while (Serial.available () > 0)
processIncomingByte (Serial.read ());
// do other stuff here like testing digital input (button presses) ...
} // end of loop
</code></pre>
|
9672 | |arduino-ide| | Remove unused boards from Arduino IDE | 2015-03-29T10:23:39.027 | <p>In the current project I'm programming simultaneously an UNO board and a Leonardo one. </p>
<p>Switching back and forth between the two boards in the <strong>Tools</strong> menu takes too much time because of the other 18 boards that I do not own anyway.</p>
<p>Is there a way to remove those boards from the Tools menu?</p>
| <p>You can open two Arduino IDE windows, and use Tools / Board to set each of them to one of the two kinds of boards you are programming. Ie, you can have multiple IDE windows open, with different options selected in each. I've programmed an Uno and a Nano device with the same program from two different windows simultaneously (ie, RX lights blinking on both boards at the same time) without problems.</p>
<p>You can use one USB cable and one port, or can use a separate USB cable for each window. You might need to use Tools / Port occasionally if the port number changes when you recable things.</p>
<p>I have the external editor option selected. Text in each Arduino IDE window updates when I click Verify or Load, rather than each time I save the file in emacs. I don't know how it works if you aren't using an external editor and have the same file open in two IDE windows.</p>
|
9674 | |power| | Where are these capacitors on the arduino schematic? | 2015-03-29T10:47:44.523 | <p>My arduino has these two capacitors</p>
<p><img src="https://i.stack.imgur.com/0wRA6.jpg" alt="enter image description here"></p>
<p>But I can't find any 47uf capacitors on the schematic. Is this not the value but instead a code? Where are these in the schematic?</p>
<p><img src="https://i.stack.imgur.com/psqR4.png" alt="enter image description here"></p>
| <p><strong>What:</strong> Looking at the schematic that you provided, it seems likely that they serve as C6 & C7. </p>
<p><strong>Why:</strong> These are shown as 100 uF each and act as "filter" capacitors for IC4, the 5V regulator.<br>
Within certain limits, such capacitors are not critical in value, and the manufacturer has probably decided that a factor of in the capacitance is probably acceptable.<br>
They are probably correct :-).</p>
<p><strong>How to check:</strong> You can check this yourself with an Ohm-meter set to the lowest Ohm range available - often = 200 Ohms max.</p>
<p>Turn off power to the board and leave it off for say 5 minutes to allow capacitors to discharge.<br>
Locate I4 and find its input and output pins or tracks leading to them. You can often get ohmic connections at vias as the tracks change board layers.<br>
IC4 pin1 will be grounded.<br>
One lead of C6 & C7 are also grounded.<br>
The pad you can see in your photo on the board edge side of the caaps is probably the -ve terminals (about 99%+ likely) (and they match the can markings)
and the "stippled" surface is almost certainly system ground. </p>
<p>If you can confirm that the two caps are connected to ground as and where described above, then:</p>
<p>Apply Ohm meter probes between the non ground lead of a capacitor and each non-ground pin in turn of IC4. One of them will be a low resistance connection if they are C6 & C7. Check the other capacitor - it should connect to the other side of IC4.<br>
Reversing the meter leads in each case may give somewhat different readings for non-hard-connected points but should be low and consistent for hard-connected by a track points. </p>
|
9678 | |power|voltage-level|usb|battery| | Run Arduino on USB and at the same time BreadBoard on higher voltage? | 2015-03-29T12:59:57.057 | <p>I am trying to design a bicycle LED lighting system, and for that I bought an Arduino yesterday (so very beginner with Arduino).</p>
<p>My final system will operate at 6V, so I plan to put everything on a breadbord and tune everything (blinking times, resistor values, etc.) and for that I want to keep my Arduino plugged to USB during development.</p>
<p>So my question is:</p>
<p>How should I connect USB-powered Arduino to a higher-voltage-powered breadbord (between 6 and 12V) safely?</p>
| <p>I think as far as i understood the problem, the system or whatever you call is will run on what ever power as long that power is not fed to the arduino that will not be a problem, just connect the two grounds together and power the arduino through the computer and connect the pins to the system accordingly. i think this will solve thus the trivial problem.</p>
|
9683 | |library| | How to share a library on Arduino Playground? | 2015-03-29T15:06:32.390 | <p>I have written an ISR-based timer library for Arduino Uno and I would like to share it on the website and get it reviewed.</p>
<p>But I am stuck on how to post it to playground.</p>
| <p>The <a href="http://playground.arduino.cc/Main/LibraryList" rel="nofollow noreferrer">Arduino Playground library list</a> is a wiki page (like everything on the playground). That means anyone can log in to edit it and add links to their own libraries. The "Log In" and "Sign Up" links are at the top right of the Arduino site. When you first go to edit a Playground page you'll be taken to a "Password required" page but don't worry, this is only to prevent spam and the password is pre-filled. You only need to click the "I'm not a robot" checkbox, wait for the green checkmark to appear, then click "Submit".</p>
<p>There are a couple of important things to note though. Firstly, the Playground library list isn't there for getting your work reviewed. It's a place to post things that are functional and ready to be used by other people. If you need someone to help with your project then you can maybe post on the Arduino forums. Alternatively, if you have specific questions, you can post here on Arduino SE.</p>
<p>If you're ready to post your library online, you also have to be aware that the Playground itself won't host your code. You can put a link there and maybe some documentation. However, you'll need to host your code somewhere else, such as <a href="https://github.com" rel="nofollow noreferrer">Github</a>.</p>
|
9696 | |arduino-uno|avr|progmem| | Unusual behaviour when moving data to PROGMEM | 2015-03-30T00:13:06.060 | <p>I've got some working code with a definition that looks like this:</p>
<pre><code>const unsigned char DynTextPositions[10][4][4] = {
...
};
</code></pre>
<p>Which is defined / referenced via a header:</p>
<pre><code>#include <avr/pgmspace.h>
#ifndef DYNTEXTPOS_H
#define DYNTEXTPOS_H
extern const unsigned char DynTextPositions[10][4][4];
#endif
</code></pre>
<p>This data is being fed into a rendering function which draws lines based on the given positions. The data is read as follows:</p>
<pre><code>float deltas[4][4];
// ...
deltas[n][k] = float(DynTextPositions[c+1][n][k] - DynTextPositions[c][n][k]) / 32.0;
</code></pre>
<p>As-is, this works just fine, as long as I've got my other scenes commented out. When I uncomment them, the combined data size seems to overflow the data segment. This is expected, because there's a fair bit of data, so I'm trying to move the <code>DynTextPositions</code> data into <code>PROGMEM</code>.</p>
<p>I've got <code>PROGMEM</code> working with some bitmaps, but it doesn't seem to work here. An example definition for a working bitmap is as follows:</p>
<pre><code>PROGMEM const unsigned char ArduinoLogo[] = { ... };
</code></pre>
<p>However, as soon as I apply the <code>PROGMEM</code> attribute to <code>DynTextPositions</code> the rendering code seems to freak out - the positions appear to be all off-screen and completely wrong.</p>
<p>The only thing I can think of is that, for some reason, the data is either being considered signed rather than unsigned, or is getting corrupted along the way. Either that or the nested array is somehow being treated as a set of pointers.</p>
<p>Any idea why this might be?</p>
| <p>Including <code><avr/pgmspace.h></code> and using the <code>PROGMEM</code> qualifier macro are only two of the steps required in order to get this to work. Since the data will no longer be available via the data bus you will need to use the various <code>pgm_read_*()</code> macros or <code>*_P*()</code> functions defined in <a href="http://www.nongnu.org/avr-libc/user-manual/group__avr__pgmspace.html" rel="nofollow"><code>avr/pgmspace.h</code></a>. These work by using the appropriate assembly code instructions to access data stored in program space, i.e. flash, on the MCU.</p>
<p>Under GCC 4.7 or higher when writing C code, the <code>__flash</code> named address space is available. Variables declared within this namespace do not require any additional steps to access them. Note that the Arduino IDE compiles as C++, and hence does not make this (or any of the <a href="https://gcc.gnu.org/onlinedocs/gcc/Named-Address-Spaces.html#AVR-Named-Address-Spaces" rel="nofollow">others</a>) available.</p>
|
9702 | |arduino-mega|arduino-ide|compile| | How to compile and upload the specific (.cpp + .h) code? | 2015-03-30T09:13:21.240 | <p>I have a specific arduino code (no .ino files) <a href="https://github.com/justintconroy/MdbBillValidator" rel="nofollow">https://github.com/justintconroy/MdbBillValidator</a> , which can't be opened by arduino IDE. How can I make & upload this code? I have an arduino 2560 mega.</p>
<p>I've created an empty <code>MdbBillValidator.ino</code> file and added these lines:</p>
<pre><code>#include "MdbBillValidator.h"
void setup() {
}
void loop() {
}
</code></pre>
<p>Here is the error message</p>
<pre><code>MdbSerial.cpp: In function ‘void __vector_37()’:
MdbSerial.cpp:289:23: error: ‘TXB8’ was not declared in this scope
MdbSerial.cpp:291:24: error: ‘TXB8’ was not declared in this scope
MdbSerial.cpp: In function ‘void __vector_52()’:
MdbSerial.cpp:314:23: error: ‘TXB8’ was not declared in this scope
MdbSerial.cpp:316:24: error: ‘TXB8’ was not declared in this scope
MdbSerial.cpp: In function ‘void __vector_55()’:
MdbSerial.cpp:339:23: error: ‘TXB8’ was not declared in this scope
MdbSerial.cpp:341:24: error: ‘TXB8’ was not declared in this scope
MdbSerial.cpp: At global scope:
MdbSerial.cpp:554:135: error: expected ‘)’ before numeric constant
MdbSerial.cpp:554:189: error: no matching function for call to ‘MdbSerial::MdbSerial(ring_buffer*, ring_buffer*, volatile uint8_t*, volatile uint8_t*, volatile uint8_t*, volatile uint8_t*, volatile uint8_t*, volatile uint8_t*, int, int, int, int, int, int, int, int, int, int, int)’
MdbSerial.cpp:554:189: note: candidates are:
MdbSerial.cpp:352:1: note: MdbSerial::MdbSerial(ring_buffer*, ring_buffer*, volatile uint8_t*, volatile uint8_t*, volatile uint8_t*, volatile uint8_t*, volatile uint8_t*, volatile uint8_t*, uint8_t, uint8_t, uint8_t, uint8_t, uint8_t, uint8_t, uint8_t, uint8_t, uint8_t, uint8_t, uint8_t, uint8_t)
MdbSerial.cpp:352:1: note: candidate expects 20 arguments, 19 provided
In file included from MdbSerial.cpp:38:0:
MdbSerial.h:52:7: note: MdbSerial::MdbSerial(const MdbSerial&)
MdbSerial.h:52:7: note: candidate expects 1 argument, 19 provided
</code></pre>
| <p>The problem is that I need to import this code just a simple usual library.</p>
|
9709 | |arduino-uno|arduino-pro-mini|communication| | How to have an Arduino communicate with 3 other Arduinos? | 2015-03-30T15:28:40.510 | <p>I was wondering how I can get 4 Arduinos in total to communicate with each-other through a wired connection. The goal is to have the master Arduino send a number 0-100 to each of the other Arduinos.</p>
<p>The master unit will be an Arduino Uno and the other 3 Arduinos will be Arduino Pro Minis.</p>
| <p><a href="https://github.com/gioblu/PJON" rel="nofollow noreferrer">PJON</a> is a bit banged serial bus protocol for multiple nodes. You may find it useful.</p>
<blockquote>
<p>PJON™ (Padded Jittering Operative Network) is an Arduino compatible,
multi-master, multi-media communications bus system. It proposes a
Standard, it is designed as a framework and implements a totally
software emulated network protocol stack that can be easily
cross-compiled on many architectures like ATtiny, ATmega, ESP8266,
Teensy, Raspberry Pi, Linux and Windows x86 machines. It is a valid
tool to quickly and comprehensibly build a network of devices</p>
</blockquote>
|
9710 | |arduino-uno|shields|wifi| | Wifi module for arduino shield | 2015-03-30T16:32:16.943 | <p>Recently I bought a <a href="http://rads.stackoverflow.com/amzn/click/B006RATC2E" rel="nofollow">B006RATC2E</a> wireless shield for my Arduino One, but didn't notice that I had to buy a wifi module as well to let it work (bad surprise as the shield already cost me $30 + travel expenses to CR). Could someone be so kind to suggest me some compatible wifi modules for the shield?</p>
<p>I'm kind of newbie in this and when I search specs for Adafruit and XBee modules, the documentation is not explicit about the compatibility with Arduino shields, so I'm stuck.</p>
<p>I don't want to buy components that would't work together (my budget is limited). Is <a href="http://rads.stackoverflow.com/amzn/click/B007R9U1QA" rel="nofollow">XBee XB24</a> a good module for the shield? Any other alternative?</p>
<p>Thanks in advance for any help!</p>
| <p>Wireless doesn't necessarily mean it's WiFi.
You should get an XBee module that explicitly states that it's a WiFi module.</p>
<p>For a cheaper alternative you can check ESP8266 WiFi modules, which you can get for $5.</p>
|
9716 | |c++|pointer| | Use pointer in calculation results in error | 2015-03-30T21:53:00.747 | <p>I'm building a project to measure/track <a href="http://en.wikipedia.org/wiki/Flyball" rel="nofollow">flyball</a> dog races.
The dogs timings are measured by photoelectric sensors at the start/finish line of the racing lane.
I have most of my code working (<a href="https://github.com/vyruz1986/FlyballSensor" rel="nofollow">available</a> on github) but I'm having some difficulties in handling very short crossings of dogs. Since I cannot realistically run a real race at home next to my development machine :-), I'm trying to build a simulator class which gives the triggers that would normally come from my photoelectric sensors.</p>
<p>I have a RaceHandler class which has the following in its header file:</p>
<pre><code>class RaceHandlerClass
{
public:
long* lRaceStartTime = &_lRaceStartTime;
private:
long _lRaceStartTime;
}
extern RaceHandlerClass RaceHandler;
</code></pre>
<p>As you can see I made a public pointer lRaceStartTime which points to the private _lRaceStartTime member variable.
This might seem stupid/strange, but it really should a private member variable, I just want to 'temporarily' make it publicly available, so that I can use it in a temporary 'simulator' class to simulate a race towards my code.</p>
<p>Then I want to use this public pointer in the Simulator class like so:</p>
<pre><code>long* lRaceStartTime = RaceHandler.lRaceStartTime;
long lRaceElapsedTime = micros() - lRaceStartTime;
</code></pre>
<p>However I get the following error when trying to compile this:</p>
<blockquote>
<p>error: invalid operands of types 'long unsigned int' and 'long int*'
to binary 'operator-'</p>
</blockquote>
<p>I'm afraid my c++ knowledge ends here and I have no clue what I should do different to fix this...
Any help would be greatly appreciated!</p>
| <p>I realise your question was but a simple query on syntax. But I would like to point out that the whole idea of object orientation is encapsulating functions and data so that external calls do not have to know about the internal-workings of that class.</p>
<p>It's common with object oriented programming to use 'getters' and 'setters' to modify private member-variables of the class. You really should not be giving a pointer to a <em>private</em> member. If you need to read/write it, add a setter function.</p>
<pre><code>class RaceHandler
{
public:
void setStartTime()
{
race_start_time = micros();
}
void setStartTime(unsigned long start_time)
{
race_start_time = start_time;
}
unsigned long getStartTime()
{
return race_start_time;
}
unsigned long getElapsedRaceTime()
{
return micros() - race_start_time;
// TODO: handle overflow of micros() after ~72 minutes
// maybe use millis() instead
}
private:
unsigned long race_start_time;
}
</code></pre>
<p>Obviously this is laborious. Some languages have special support for getters and setters to provide the functionality with less syntax. </p>
<p>Time is always positive, use an unsigned long. As people have already said, millis() & micros() return an unsigned long too.</p>
<pre><code>RaceHandler race1;
race1.setStartTime();
[...]
unsigned long elapsed_time = race1.getElapsedRaceTime();
</code></pre>
|
9737 | |serial|softwareserial| | What do symbols like UCSR0C, UMSEL01, etc. means? | 2015-03-31T09:23:34.667 | <p>I have a code with a connection to serial port:</p>
<pre><code>// Set baud rate
UBRR0H = UBRRH_VALUE;
UBRR0L = UBRRL_VALUE;
// Disable USART rate doubler (arduino bootloader leaves it enabled...)
UCSR0A &= ~(1 << U2X0);
// Set async, no parity, 1 stop, 9bit
UCSR0C = (0<<UMSEL01)|(0<<UMSEL00)|(0<<UPM01)|(0<<UPM00)|(0<<USBS0)|(1<<UCSZ01)|(1<<UCSZ00);
UCSR0B |= (1<<UCSZ02); // 9bit
// Enable rx/tx
UCSR0B |= (1<<RXEN0)|(1<<TXEN0);
</code></pre>
<p>I see the comments but I want to know exactly what does these chunks means. Is there any complete documentation about these symbols?</p>
| <p>I strongly recommend you to read the datasheet. You are confusing UART module with GPIO module. Once you use one pin for one purpose (say serial comunication) you cannot use it for another thing (say general I/O to read a physical button state). Of course it is possible if you write your code in a way it changes all the registers (the ones you call "symbols") on excecution time. But just be carefull that the routines that used those pins for UART don't execute meanwhile! </p>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.