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
|
---|---|---|---|---|---|
17480
|
|atmega32u4|digital-analog-conversion|
|
Using Analog Comparator on ATmega32u4
|
2015-11-05T01:51:44.513
|
<p>I am (currently) parsing a PPM analog signal using an Arduino Uno R3 using the analog comparator ASCR and analog hardware interrupts using AIN0 and AIN1. I am applying a specific negative comparison voltage using a linear voltage regulator on AIN0 and the signal on AIN1.</p>
<p><strong>Code snippets:</strong></p>
<p><em>setup</em></p>
<pre><code> ACSR = B00011011;
</code></pre>
<p><em>outside other closures</em></p>
<pre><code>ISR(ANALOG_COMP_vect) {
CRCArduinoPPMChannels::INT0ISR();
}
</code></pre>
<p>I am trying to move this project to an Arduino (compatible) <a href="https://www.sparkfun.com/products/12640" rel="nofollow noreferrer">Pro Micro from SparkFun</a>. The <a href="http://cdn.sparkfun.com/datasheets/Dev/Arduino/Boards/ATMega32U4.pdf" rel="nofollow noreferrer">datasheet</a> specifies AIN0 on ATmega32u4 pin 1 but do not see a reference to AIN1. </p>
<p>The datasheet outlines use of the analog comparator on page 289:</p>
<blockquote>
<p>AIN+ can be connected either to the AIN0 (PE6) pin, or to the internal
Bandgap reference. AIN- can only be connected to the ADC multiplexer.</p>
</blockquote>
<p>I have connected the signal to Arduino pin 7, the comparison voltage to Arduino pin 20 (analog 2) and set the following options of the ADMUX register:</p>
<pre><code>ADMUX = B11000101;
</code></pre>
<p>The interrupts trigger but the comparator voltage (AIN-) is not being observed. Any help would be appreciated.</p>
|
<p>AIN- won't be connected to the ADC mux unless ACME is set and ADEN is cleared. Don't forget to do so.</p>
|
17486
|
|serial|programming|arduino-due|python|
|
Graph plotting on Python using Tkinter Canvas
|
2015-11-05T04:35:35.227
|
<p>I'm trying to plot a graph with python using the canvas widget, I'm currently sending data in from an arduino sensor sketch ..does anyone have an idea on how I can plot this graph in real time on Python using canvas. I've read up on it but I'm having problems with unpacking the x , y and z axis data and looping it to updating in real time. Below is the arduino sketch.And also the skeleton of the Tkinter canvas sketch. Thanks!!</p>
<pre><code>AcceleroMMA7361 ski;
int x;
int y;
int z;
void setup(){
Serial.begin(115200);
ski.begin(13, 12,11,10, A0, A1, A2);
ski.setARefVoltage(3.3);
ski.setSensitivity(HIGH);
ski.calibrate();
}
void loop(){
x = ski.getXRaw();
y = ski.getYRaw();
z = ski.getZRaw();
Serial.print("\nx: ");
Serial.println(x);
Serial.print("\ty: ");
Serial.print(y);
Serial.print("\tz: ");
Serial.print(z);
delay(10); //(make it readable)
}//End of Arduino Sketch
from Tkinter import *
import serial #import Serial Library
import numpy as np # Import numpy
ardoData = serial.Serial('COM4', 115200)
accelX1 = [] #to hold the incoming axis data from the arduino
accelY1 = []
accelZ1 = []
class GraphException(Exception):
def __init__(self, string):
Exception.__init__(self, string)
class Smoking(Canvas):
def __init__(self, master, FrameTitle, Col, Row, Height):
Canvas.__init__(self, master)
self.FrameTitle = FrameTitle
self.x1Axis = range(1001)
self.y1Axis = range(1001)
self.z1Axis = range(1001)
self.Line1 = range(1001)
self.Line2 = range(1001)
self.Line3 = range(1001)
self.configure(height=Height, width=750, bg='grey', bd=3, relief=GROOVE)
self.grid()
self.grid_propagate(0)
self.Col = Col
self.Row = Row
self.place(y=Col, x=Row)
self.create_text(380, 20, text=self.FrameTitle, fill = 'black')
for i in range(0, 1001):
self.Line1[i] = self.create_line(-10+(i*10), 90, 0+(i*10), 90, fill='blue', width=0)
self.Line2[i] = self.create_line(-10+(i*10), 90, 0+(i*10), 90, fill='red', width=0)
self.Line3[i] = self.create_line(-10+(i*10), 90, 0+(i*10), 90, fill='yellow', width=0)
def LiveValues(self,accelX1, accelY1, accelZ1, Centerline = False, Dritter = False):
for x in range(1, 59):
for i in np.arange(1, 1001, 1):
while(ardoData.inWaiting() == 0):
pass #do nothing
ardoString = ardoData.readline()
dataArray = ardoString.strip().strip('\n') #Split into an array called dataArray and strip off any spaces
# Ensure that you are not working on empty line
if ardoString:
dataArray = ardoString.split(",")
if len(dataArray) > 1:
self.x1Axis = int(dataArray[0])
self.y1Axis = int(dataArray[1])
self.z1Axis = int(dataArray[2])
accelX1.append(self.x1Axis)
accelY1.append(self.y1Axis)
accelZ1.append(self.z1Axis)
for x in range(0, 1001):
self.coords(self.Line1[x], -10+(x*10), self.accelX1[x], (x*10), self.accelX1[x+1])
self.coords(self.Line2[x], -10+(x*10), self.accelY1[x], (x*10), self.accelY1[x+1])
self.coords(self.Line3[x], -10+(x*10), self.accelZ1[x], (x*10), self.accelZ1[x+1])
# Create and run the GUI
root = Tk()
app = Smoking(root, "Smooth Sailing", 1000, 1000, 1000)
app.mainloop()
</code></pre>
<p>So after working with the answer given on the post I ended up with a Line graph that is not reactive, I understand that I have to tweak the code to suit the range of values I am getting which is shown below. I increased the limit as indicated by @patthoyts but I still couldn't get either lines to show up on the canvas and to even be reactive ( what i mean by that is to respond to the movement of the sensor). Also, do bear with me Editors!, if I'm going about editing this question the wrong way, is just that I'm quite desperate to have this issue resolved. Does anyone have any clue as to how I could resolve this issue. Thanks PS: I added both images , that of my data stream and the image on the canvas.
<a href="https://i.stack.imgur.com/V5pdE.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/V5pdE.png" alt="enter image description here"></a>
<a href="https://i.stack.imgur.com/xKX47.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/xKX47.png" alt="enter image description here"></a></p>
|
<p>To generate a useful example I've setup an Arduino Nano with a magnetic orientation sensor and have it output 3 values per line for the X, Y and Z field strengths. It prints 1 line every 50ms and the following python tkinter script plots this. It started as your python code above but it has been reworked to be more pythonic. The result looks like this:
<a href="https://i.stack.imgur.com/3wnW3.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/3wnW3.png" alt="screenshot of tkinter plot"></a></p>
<p>Call the script with the comport and speed. eg: <code>python magplot.py COM21 19200</code></p>
<pre><code>#!/usr/bin/python
#
# Read stream of lines from an Arduino with a magnetic sensor. This
# produces 3 values per line every 50ms that relate to the orientation
# of the sensor. Each line looks like:
# MAG 1.00 -2.00 0.00
# with each data line starting with "MAG" and each field separated by
# tab characters. Values are floating point numbers in ASCII encoding.
#
# This script supports both Python 2.7 and Python 3
from __future__ import print_function, division, absolute_import
import sys
if sys.hexversion > 0x02ffffff:
import tkinter as tk
else:
import Tkinter as tk
from serial import Serial
class App(tk.Frame):
def __init__(self, parent, title, serialPort):
tk.Frame.__init__(self, parent)
self.serialPort = serialPort
self.npoints = 100
self.Line1 = [0 for x in range(self.npoints)]
self.Line2 = [0 for x in range(self.npoints)]
self.Line3 = [0 for x in range(self.npoints)]
parent.wm_title(title)
parent.wm_geometry("800x400")
self.canvas = tk.Canvas(self, background="white")
self.canvas.bind("<Configure>", self.on_resize)
self.canvas.create_line((0, 0, 0, 0), tag='X', fill='darkblue', width=1)
self.canvas.create_line((0, 0, 0, 0), tag='Y', fill='darkred', width=1)
self.canvas.create_line((0, 0, 0, 0), tag='Z', fill='darkgreen', width=1)
self.canvas.grid(sticky="news")
self.grid_rowconfigure(0, weight=1)
self.grid_columnconfigure(0, weight=1)
self.grid(sticky="news")
parent.grid_rowconfigure(0, weight=1)
parent.grid_columnconfigure(0, weight=1)
def on_resize(self, event):
self.replot()
def read_serial(self):
"""
Check for input from the serial port. On fetching a line, parse
the sensor values and append to the stored data and post a replot
request.
"""
if self.serialPort.inWaiting() != 0:
line = self.serialPort.readline()
line = line.decode('ascii').strip("\r\n")
if line[0:3] != "MAG":
print(line) # line not a valid sensor result.
else:
try:
data = line.split("\t")
x, y, z = data[1], data[2], data[3]
self.append_values(x, y, z)
self.after_idle(self.replot)
except Exception as e:
print(e)
self.after(10, self.read_serial)
def append_values(self, x, y, z):
"""
Update the cached data lists with new sensor values.
"""
self.Line1.append(float(x))
self.Line1 = self.Line1[-1 * self.npoints:]
self.Line2.append(float(y))
self.Line2 = self.Line2[-1 * self.npoints:]
self.Line3.append(float(z))
self.Line3 = self.Line3[-1 * self.npoints:]
return
def replot(self):
"""
Update the canvas graph lines from the cached data lists.
The lines are scaled to match the canvas size as the window may
be resized by the user.
"""
w = self.winfo_width()
h = self.winfo_height()
max_X = max(self.Line1) + 1e-5
max_Y = max(self.Line2) + 1e-5
max_Z = max(self.Line3) + 1e-5
max_all = 200.0
coordsX, coordsY, coordsZ = [], [], []
for n in range(0, self.npoints):
x = (w * n) / self.npoints
coordsX.append(x)
coordsX.append(h - ((h * (self.Line1[n]+100)) / max_all))
coordsY.append(x)
coordsY.append(h - ((h * (self.Line2[n]+100)) / max_all))
coordsZ.append(x)
coordsZ.append(h - ((h * (self.Line3[n] + 100)) / max_all))
self.canvas.coords('X', *coordsX)
self.canvas.coords('Y', *coordsY)
self.canvas.coords('Z', *coordsZ)
def main(args = None):
if args is None:
args = sys.argv
port,baudrate = 'COM4', 115200
if len(args) > 1:
port = args[1]
if len(args) > 2:
baudrate = int(args[2])
root = tk.Tk()
app = App(root, "Smooth Sailing", Serial(port, baudrate))
app.read_serial()
app.mainloop()
return 0
if __name__ == '__main__':
sys.exit(main())
</code></pre>
<h1>Update</h1>
<p>Looking at the updated question it is clear that the new Tkinter code is not updating the display. In all windowing systems it is essential that the application thread is allowed to process events regularly. This is why the example code above uses the Tk <code>after()</code> method to add calls to the event queue. The <code>read_serial()</code> function checks to see if any data is available and if not <em>schedules a retry later</em>. This is done by using <code>after()</code> to request the same method is called again in 10ms time. During that 10ms delay the Tk application processes all the other windowing system events like mouse movement, keyboard input and crucially expose and painting events.</p>
<p>The same method is used to call the <code>replot()</code> method once we have updated the list of data items. In this case <code>after_idle()</code> has been used which means schedule this function call as soon as nothing else is happening.</p>
<p>The act of changing the canvas line coordinates will cause further events to be raised by Tk which affect the display only once they are processed by the event loop. If we never process the events, nothing will appear on screen.</p>
|
17497
|
|led|pwm|
|
How to build a high-frequency (>20kHz) driver for LEDs?
|
2015-11-05T15:55:18.153
|
<p>I'd like to build a LED lighting for my house. I've made preliminary tests and I've realized that my 12V transformer emits a considerable electric hum at the Arduino's PWM frequency range (PWM signal from Arduino gets amplified by external amplifier powered by the transformer). </p>
<p>I know, that I can reduce the audible noise if I will drive the PWM at higher frequency, beyond the human ear's audible range.</p>
<p>AFAIK Arduino itself is not able to give me 8-bit PWM at the >20kHz range. Do you know any feasible hardware high frequency PWMs that will work with the Arduino?</p>
|
<p>I am not into hardware but the way we handle it was by using a external PWM designed for LEDs and control that, using an Arduino. The LED driver we used was a TLC5940, see <a href="http://www.ti.com/lit/ds/symlink/tlc5940.pdf" rel="nofollow">TLC5940 16-Channel LED Driver With DOT Correction and Grayscale PWM Control</a>. This one is controllable using the SPI bus. </p>
<p>There are several libaries implementing the protocol, i.e <a href="https://github.com/PaulStoffregen/Tlc5940" rel="nofollow">PaulStoffregen/Tlc5940</a>.</p>
<p>See <a href="http://playground.arduino.cc/Learning/TLC5940" rel="nofollow">Playground from Arduino - TLC5940</a> for more information.</p>
|
17498
|
|bluetooth|relay|
|
Having problems with HC-05 and three relays
|
2015-11-05T16:09:06.967
|
<p>I'm trying to control three relays with the Arduino Uno rev3 and a HC-05 bluetooth module from Elecfreaks.</p>
<p>I've wrote this code: </p>
<pre><code>// the comments are the part of the code that I use to replace the Serial by default to be able to use the HC-05 module
//#include <SoftwareSerial.h>
int relay1 = 2;
int relay2 = 3;
int relay3 = 4;
int relay1estatus = 0;
int relay2estatus = 0;
int relay3estatus = 0;
char command;
//SoftwareSerial bluetooth(5,6);
void setup() {
Serial.begin(9600); //bluetooth.begin(9600);
pinMode(relay1, OUTPUT);
pinMode(relay2, OUTPUT);
pinMode(relay3, OUTPUT);
digitalWrite(relay1, LOW);
digitalWrite(relay2, LOW);
digitalWrite(relay3, LOW);
}
void loop() {
while(Serial.available() > 0){ //bluetooth.available()
command = (byte)Serial.read(); //(byte)bluetooth.read();
Serial.println(command); //bluetooth.println(command)
if (command == 'a'){
if (relay1estatus == 0){
digitalWrite(relay1, HIGH);
relay1estatus = 1;
}else{
digitalWrite(relay1, LOW);
relay1estatus = 0;
}
}
if (command == 'b'){
if (relay2estatus == 0){
digitalWrite(relay2, HIGH);
relay2estatus = 1;
}else{
digitalWrite(relay2, LOW);
relay2estatus = 0;
}
}
if (command == 'c'){
if (relay3estatus == 0){
digitalWrite(relay3, HIGH);
relay3estatus = 1;
}else{
digitalWrite(relay3, LOW);
relay3estatus = 0;
}
}
}
}
</code></pre>
<p>The problem is that this code works perfectly using the Arduino IDE serial monitor, but when I try it using instead of the default serial methods, the SoftwareSerial ones it doesn't work.</p>
<p>Doesn't work in a very strange way because I can switch one by one the relays between on or off but, when I have two of them activated seems like freezes, I can't switch the third one on or off and neither I can switch the other two again.</p>
<p>To send the 'commands' through bluetooth I use the Bluetooth Terminal app available in the PlayStore.
(I've just posted the same question in stackoverflow but now I think here's the best place to ask it)</p>
|
<p>I don't see a problem with the code indicated for bluetooth; if that code is indeed ok, then probably you should look for hardware issues; first, look for low +5V when multiple relays are turned on. (Attach a voltmeter or a scope to +5, see if it changes when a second relay comes on, etc.) Second, look (with a storage scope) for glitches when the relays switch. If you don't have a storage scope, try testing with a separate power supply for the relays. (Tie the grounds of things together, but give the Arduino and the HC-05 +V that's isolated from relay +V.)</p>
<p>More seriously, your code is overweight. For example, replace</p>
<pre><code> if (relay1estatus == 0){
digitalWrite(relay1, HIGH);
relay1estatus = 1;
} else {
digitalWrite(relay1, LOW);
relay1estatus = 0;
}
</code></pre>
<p>with</p>
<pre><code> relay1estatus = 1 - relay1estatus;
digitalWrite(relay1, relay1estatus);
</code></pre>
|
17512
|
|arduino-uno|uart|ftdi|programmer|
|
Using Arduino UNO as FTDI programmer for 9DOF Razor IMU
|
2015-11-05T23:23:07.463
|
<p>I am trying to upload some code to the ATmega328 on Sparkfun's 9DOF Razor IMU. Because I don't have an FTDI board at hand I was trying to use my UNO by "grounding" the <code>RESET</code> pin. Communicating with the 9DOF works well (it has some sample firmware loaded):</p>
<p><img src="https://i.stack.imgur.com/Y6zBt.png" width="400"></p>
<p><strong>So here's the problem:</strong></p>
<p>When I try to program the ATmega328, the Arduino IDE gives e the following error:</p>
<p><code>avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x0d</code></p>
<p><img src="https://i.stack.imgur.com/HMOUK.png" width="300">
<img src="https://i.stack.imgur.com/kyOYw.jpg" width="240"></p>
<p>What am I doing wrong?</p>
|
<p>What you're missing is the signal that resets the ATMega so it can enter the bootloader. That signal is the one that goes to the DTR pin of the 9DOF and would normally be sent to the reset pin on your Arduino (that you are grounding).</p>
<p>What you need to do is reset the 9DOF just as it's about to start trying to upload the code. Timing is critical - you get about a second or so of leeway where the bootloader is actually available for avrdude to talk to.</p>
<p>Alternatively you can try and find a point on your Arduino board where the DTR signal from the USB interface chip is available <em>before</em> it passes through the capacitor to the RESET pin of the Arduino and take a wire from there (wherever that may be) to the DTR pin of the 9DOF.</p>
|
17514
|
|arduino-mega|avr|isr|
|
Timer (or other) interrupt happens while servicing an interrupt - how to accurately handle the second one?
|
2015-11-06T01:08:33.153
|
<p>This seems like a simple question but I'm not finding an answer so far: at a high level, say I have a timer interrupt and some input interrupt. The input arrives, the ISR is entered, interrupts are (automatically by default?) disabled, I service the input (quickly!), but while that's going on a timer used for some other purpose fires. I don't want to miss that timer but because interrupts are disabled my input processing won't get interrupted for it.</p>
<p>I exit the input ISR and interrupts are (automatically?) re-enabled. Assuming the timer is uncomplicated (it wouldn't overflow twice during my input ISR) how do I accurately handle the fact that it overflowed during my input ISR and I "missed" it?</p>
<p>Would this differ if instead of the timer I simply had a second input2 that similarly might fire during my input1 processing (but would present a useful input long enough to process after input1, presuming I knew it triggered)?</p>
<p>I'm not looking to nest interrupts here, just to understand what happens when an interrupt happens during another ISR which has temporarily disabled them - do they pend and fire after the blocking ISR returns, or are they just lost?</p>
|
<p>Q1:</p>
<blockquote>
<p>... exit the input ISR and interrupts are (automatically?) re-enabled</p>
</blockquote>
<p>Yes, the RETI (return from interrupt) instruction enables interrupts. See third paragraph of section 7.7 in <a href="http://www.atmel.com/images/atmel-8271-8-bit-avr-microcontroller-atmega48a-48pa-88a-88pa-168a-168pa-328-328p_datasheet_complete.pdf" rel="nofollow">Atmel's document #8271</a> (a 650-page spec sheet for the Atmega 48, 88, 168, 328 series), which says:</p>
<blockquote>
<p>When an interrupt occurs, the Global Interrupt Enable I-bit is cleared and all interrupts are disabled. The user software can write logic one to the I-bit to enable nested interrupts. All enabled interrupts can then interrupt the current interrupt routine. The I-bit is automatically set when a Return from Interrupt instruction – RETI – is executed.</p>
</blockquote>
<p>Q2:</p>
<blockquote>
<p>Assuming the timer is uncomplicated (it wouldn't overflow twice during my input ISR) how do I accurately handle the fact that it overflowed during my input ISR and I "missed" it?</p>
</blockquote>
<p>If the timer is running a clock, set the timer control bits to automatically reload the count register upon each overflow (or underflow). That will leave a full count period for processing each timer interrupt.</p>
<p>That is, you can pre-load a next-timer-count (I think it can be different from the current count if necessary), so the timer can start its next interval automatically. If the timer is used for some purpose more complicated than that, you may need a nested interrupt.</p>
<p>Q3:</p>
<blockquote>
<p>Would this differ if instead of the timer I simply had a second input2 that similarly might fire during my input1 processing (but would present a useful input long enough to process after input1, presuming I knew it triggered)?</p>
</blockquote>
<p>If indeed input2 sticks around long enough to process after input1 processing is done, no problem. Its interrupt will occur after the first interrupted code sequence executes one more instruction after the RETI occurs. (See paragraph 6 of section 7.7 in doc8271.)</p>
<p>If input2 is brief, several different things can happen. (a) If it is shorter than a clock cycle, in general it won't trigger an interrupt. (b) If it is a level-interrupt-triggering event on INT0 or INT1 that ends while another interrupt is being processed, it won't trigger an interrupt. (See discussion on page 72, section 13.2.3, of doc8271 of INTF0 and INTF1 being clear for level interrupts.) (c) If it is an interrupt-flag-setting event that sets a flag and ends while another interrupt is being processed, it will trigger an interrupt after the global interrupt flag is set, unless current processing clears its flag.</p>
<p>I think the above accurately states what happens on Atmega devices, but I suggest you also see doc8271 – and run tests – to see for yourself. Here is part of what paragraphs 4 and 5 of section 7.7 in doc8271 say regarding (b) and (c):</p>
<blockquote>
<p>There are basically two types of interrupts. The first type is triggered by an event that sets the Interrupt Flag. ... Interrupt Flags can also be cleared by
writing a logic one to the flag bit position(s) to be cleared. If an interrupt condition occurs while the
corresponding interrupt enable bit is cleared, the Interrupt Flag will be set and remembered until the interrupt is enabled, or the flag is cleared by software. Similarly, if one or more interrupt conditions occur while the Global Interrupt Enable bit is cleared, the corresponding Interrupt Flag(s) will be set and remembered until the Global Interrupt Enable bit is set, and will then be executed by order of priority.</p>
<p>The second type of interrupts will trigger as long as the interrupt condition is present. These interrupts do not necessarily have Interrupt Flags. If the interrupt condition disappears before the interrupt is enabled, the
interrupt will not be triggered.</p>
</blockquote>
|
17535
|
|serial|atmega328|avr-gcc|pl2303hx|
|
Why serial communication does not work on atmega168/328p?
|
2015-11-06T15:44:37.100
|
<p>I expect from the following program <code>serial.c</code> to light the led on if I send key <code>1</code> from terminal, and light the led off when I send key <code>0</code> from terminal:</p>
<pre><code>#define F_CPU 16000000UL
#define BAUD 9600
#include <avr/io.h>
char data;
void main(void) {
#include <util/setbaud.h>
UBRR0H = UBRRH_VALUE;
UBRR0L = UBRRL_VALUE;
UCSR0B |= (1<<RXEN0);
UCSR0C |= (1<<UCSZ01)|(1<<UCSZ00);
DDRB |= (1<<PB1);
while(1) {
while(!(UCSR0A&(1<<RXC0)));
data = UDR0;
if (data=='0') PORTB &= ~(1<<PB1);
if (data=='1') PORTB |= (1<<PB1);
}
}
</code></pre>
<p>I use the following commands to compile and burn all the programs:</p>
<pre><code>avr-gcc -Os -mmcu=atmega328p -c -o serial.o serial.c
avr-ld -o serial.elf serial.o
avr-objcopy -O ihex serial.elf serial.hex
avrdude -c usbasp -p atmega328p -U flash:w:serial.hex
</code></pre>
<p>The output of avrdude is the following:</p>
<pre><code>$ avrdude -c usbasp -p atmega328p -U flash:w:serial.hex
avrdude: AVR device initialized and ready to accept instructions
Reading | ################################################## | 100% 0.00s
avrdude: Device signature = 0x1e950f
avrdude: NOTE: "flash" memory has been specified, an erase cycle will be performed
To disable this feature, specify the -D option.
avrdude: erasing chip
avrdude: reading input file "serial.hex"
avrdude: input file serial.hex auto detected as Intel Hex
avrdude: writing flash (12 bytes):
Writing | ################################################## | 100% 0.03s
avrdude: 12 bytes of flash written
avrdude: verifying flash memory against serial.hex:
avrdude: load data flash data from input file serial.hex:
avrdude: input file serial.hex auto detected as Intel Hex
avrdude: input file serial.hex contains 12 bytes
avrdude: reading on-chip flash data:
Reading | ################################################## | 100% 0.02s
avrdude: verifying ...
avrdude: 12 bytes of flash verified
avrdude: safemode: Fuses OK (E:07, H:DE, L:FF)
avrdude done. Thank you.
</code></pre>
<p>For serial connection I tried PL2302 and FT232RL usb-com adapters - the effect is always the same.</p>
<p>Terminal settings on the computer are correct (9600,8N1).</p>
<p>avr-gcc version 4.8.1
avrdude version 6.1</p>
<p>Why the very first program in this question does not work as needed and what should be changed in it to achieve the desired behavior?</p>
|
<p>The problem you have is that your baud rate is not being set right.</p>
<p>You only have part of the settings you need. There is a third macro in the setbaud.h file that you need to take account of: <code>USE_U2X</code>.</p>
<p>That defines whether or not you need to set or clear the U2X0 bit of UCSRA0. If that is set wrong then your baud rate will be either twice or half what you want it to be - in this case it's coming out as twice.</p>
<p>Modify your code to assign the baud rate like this:</p>
<pre><code>#include <util/setbaud.h>
UBRR0H = UBRRH_VALUE;
UBRR0L = UBRRL_VALUE;
#if USE_U2X
UCSR0A |= (1<<U2X0);
#else
UCSR0A &= ~(1<<U2X0);
#endif
UCSR0B |= (1<<RXEN0);
UCSR0C |= (1<<UCSZ01)|(1<<UCSZ00);
</code></pre>
<p>Then you should be able to receive characters.</p>
<p>In the actual header file in question there is a large number of comments and instructions, including this:</p>
<blockquote>
<p>Assuming that the requested BAUD is valid for the given F_CPU then
the macro UBRR_VALUE is set to the required prescaler value. Two
additional macros are provided for the low and high bytes of the
prescaler, respectively: UBRRL_VALUE is set to the lower byte of
the UBRR_VALUE and UBRRH_VALUE is set to the upper byte. <strong>An
additional macro USE_2X will be defined. Its value is set to 1 if
the desired BAUD rate within the given tolerance could only be
achieved by setting the U2X bit in the UART configuration. It will
be defined to 0 if U2X is not needed.</strong></p>
</blockquote>
<p>My resulting UART configuration, which may be being affected by the bootloader, is:</p>
<pre><code>UBRR0H: 0x00
UBRR0L: 0x67
UCSR0A: 0x20
UCSR0B: 0x10
UCSR0C: 0x06
</code></pre>
<p>That equates to <code>data register empty</code>, <code>RX enabled</code>, <code>8-bit</code>.</p>
<p>To my mind that is equal to the values being manually set in the code, so shouldn't be a problem.</p>
|
17538
|
|bluetooth|arduino-nano|
|
Computer to multiple arduino bluetooth modules
|
2015-11-06T16:51:36.780
|
<p>Im going to take part in a competition called IEEE Very Small Soccer and I need to set up a communication between my computer, that will run visual and strategy algorithms, and send some commands to 3 Arduinos, which will be the players. Most people use the Xbee module to send data to the Arduinos, so I was wondering why not use the Bluetooth module instead, once it is so much cheaper and the difference in power consumption isn't so big, the only drawback would be the working range, which is 10m, if Im correct... However, if the distance is really 10m, not 5m It will be ok, because the computer is always close to the robots.</p>
<p>Summing up, my questions are:</p>
<ol>
<li>Can I use a computer to send data to 3 Arduinos at the same time?</li>
<li>What is the real working range of the Bluetooth module?</li>
<li>Any suggestions or tips? =D</li>
</ol>
<p><a href="https://i.stack.imgur.com/0fjsE.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/0fjsE.png" alt="IEEE Very Small Size Soccer schematic" /></a>?</p>
|
<ol>
<li>yes, you can, this is what happens normally in a crowded area where multiple people use their phones with bluetooth headsets, for example.</li>
<li><p>if you believe <a href="https://en.wikipedia.org/wiki/Bluetooth" rel="nofollow">the claims</a> typical 10m max 100m but in practice there are a number of factors:</p>
<ul>
<li>Quality of the HW design of the antennas</li>
<li>Signal to noise ratio due to other radios operating in the same area</li>
<li>Obstacles in the path</li>
<li>Responsiveness and throughput required by your application</li>
<li>etc.</li>
</ul></li>
<li><p>you could consider other options, like <a href="http://hallard.me/nrf24l01-real-life-range-test/" rel="nofollow">this module</a>, which is basically the same, from the perspective of transferring data. Also <a href="http://www.esp8266.com/" rel="nofollow">wifi</a> could work, if you are allowed to setup your own access point.</p></li>
</ol>
|
17557
|
|relay|current|
|
How to measure relay current draw from Arduino
|
2015-11-07T12:14:27.317
|
<p>How does one measure the amount of current a relay is drawing from an Arduino? </p>
<p>Do I connect a multimeter in series with the digital pin to which the relay 'IN1' is connected (in this case pin 7), the 5V pin or GND pin?</p>
<p>Provisional testing gives me the following results (when the relay is ON):</p>
<ol>
<li>Pin 7: <strong>3.93 mA</strong></li>
<li>5V pin: <strong>70.2 mA</strong></li>
<li>GND pin: <strong>66.8 mA</strong></li>
</ol>
<p>Also, assuming I pull more than 40 mA through digital pin 7 for a number of seconds, is the pin likely to fail immediately? Or slowly degrade over time?</p>
|
<p>Have you noticed how the 5V current is, give or take a little inaccuracy on the part of your ammeter, the sum of the other two currents?</p>
<p>Without knowing what relay you are talking about, my guess is it is one of the SainSmart 5V relay modules with opto-coupler. Those, by default, use a common 5V input and split it between the opto-coupler (and then into your digital pin to be sunk through ground) and the relay to ground. Therefore the 70mA is split between 66mA through the relay and 4mA through the digital IO pin.</p>
<p>So the correct place to measure the total current in this instance is the 5V pin since that is the common point for the circuit.</p>
<p>In answer to your second question, <em>read the datasheet</em>. It quite clearly states:</p>
<blockquote>
<p>Although each I/O port can sink more than the test conditions (20 mA at VCC = 5V, 10 mA at V CC = 3V) under steady state conditions (non-transient), the following must be observed:</p>
<p>ATmega48PA/88PA/168PA/328P:</p>
<ol>
<li>The sum of all I OL , for ports C0 - C5, ADC7, ADC6 should not exceed 100 mA.</li>
<li>The sum of all I OL , for ports B0 - B5, D5 - D7, XTAL1, XTAL2 should not exceed 100 mA.</li>
<li>The sum of all I OL , for ports D0 - D4, RESET should not exceed 100 mA.</li>
</ol>
<p>If IOL exceeds the test condition, VOL may exceed the related specification. Pins are not guaranteed to sink current greater than the listed test condition.</p>
</blockquote>
<p>And also a similar note for sourcing current.</p>
<p>So although they <em>can</em> sink or source more than 20mA, and theoretically up to 40mA, anything more than 20mA is not guaranteed and should be avoided.</p>
<p>Basically overcurrents cause increased heat dissipation in the MOSFETs which causes the internals to break down. Hence the note about <em>under steady state conditions</em>. </p>
<p>So sourcing or sinking more than 20mA for longer than a few ms is asking for trouble. More than 40mA is just being irresponsible.</p>
<p>Furthermore, the MOSFETs in the IO pins act like resistors when turned on. As you should know, according to Ohm's Law, the voltage across a resistor is proportional to the current through the resistor. Increase the current and you increase the voltage across the resistor. Since that resistance is in series with your circuit that voltage gets subtracted from your available voltage on the IO pin - so drawing too much current will cause the voltage to drop (or rise for sinking) below (above) the specifications for the logic voltage for that IO pin. So not only do you risk damage to the IO pin and other parts of the chip through overheating, but you also then operate outside the specifications for the logic levels which can cause things that you are communicating with to not work right.</p>
|
17559
|
|atmega328|
|
Why were Atmel MCUs used for Arduino?
|
2015-11-07T12:41:06.527
|
<p>Atmel microcontrollers are not cheap compared to STM and Microchip. Why did Arduino select Atmel MCUs such as atmega328 and atmega2560 on their board out of so many alternatives?</p>
|
<p>Simply because the Wiring system that Arduino stole was written for the Atmel chips.</p>
<p>Arduino didn't "invent" the Arduino system - they just took an existing system called Wiring and adapted it slightly and branded it Arduino. </p>
|
17567
|
|arduino-mega|
|
creating array using string name
|
2015-11-07T15:47:26.200
|
<p>I appreciate if someone can help me.
I have a function that counts the time and I would like to store values according to the day.</p>
<p><code>For example: day_7.11.2015 = [gain = 100.23, cost = 78.0 ...]
day_8.11.2015 = ...</code></p>
<p>I do not know how can I create an array with these values taking as input the day, month and year. Does anyone have any idea?</p>
<p><code>String test = "day_" + String(day) + "." + String(month) + "." + String(year);
float String(test)[] = {11.2, 10, 20, 31.2};
Serial.println(test);</code></p>
<p>Thanks a lot!</p>
|
<p>What you're talking about is often called a <em>Hash</em> or a <em>Map</em> or sometimes both together as a <em>HashMap</em>.</p>
<p>Unfortunately it's a facility that isn't supported in the Arduino C++ language</p>
<p>There are <code>map</code> objects available in normal C++, but they are incredibly expensive to use with regards to memory and they just aren't practical for use on a small microcontroller with memory measured in the kilobytes.</p>
<p>The closest you can probably get is to "invert" the storage, so you have a list of values that happen to be in date order (because that's when you added them) but the "key", a simple sequential number, doesn't define the date. Instead you store the date inside the array along with the data - assuming you really need to know the date.</p>
<p>A good concept to get to grips with for this is the <em>struct</em>. This is a custom data type which you define and can store a number of other different data types within itself. You can then make an array or linked list out of those new data types.</p>
<p>For instance, you may have:</p>
<pre><code>typedef struct {
int year;
byte month;
byte day;
float gain;
float cost;
} Data;
</code></pre>
<p>You can then create variables of type "Data" and assign values to the items within it:</p>
<pre><code>Data myEntry;
myEntry.year = 2015;
myEntry.month = 11;
myEntry.day = 7;
myEntry.gain = 100.23;
myEntry.cost = 78.0;
</code></pre>
<p>Or assign them directly at creation time:</p>
<pre><code>Data myEntry = {2015, 11, 7, 100.23, 78.0};
</code></pre>
<p>If you wanted to store 100 days' worth of data you could use an array:</p>
<pre><code>Data myArray[100];
</code></pre>
<p>Then you access each slice:</p>
<pre><code>myArray[0].year = 2015;
... etc ...
</code></pre>
<p>I mentioned above "assuming you really need to know the date". Most of the time with this kind of method you really don't need to store the date. If you have one entry per day and you know <em>when you started gathering data</em> then you know that each entry is one day more than the one before it - so you know that the tenth entry is ten days later than when you started gathering data. Alternatively, if you have a 100 entry circular array (that is, when you reach the end of the array you start filling from the bottom again, so you keep the last 100 days' worth of data) and you know what the date is <em>today</em> you can count backwards from today to work out what date each entry is.</p>
|
17574
|
|arduino-leonardo|
|
Arduino Leonardo bugs and lack of removable microcontroller
|
2015-11-07T18:37:47.310
|
<p>Following one of the <a href="http://www.tested.com/tech/robots/456466-know-your-arduino-guide-most-common-boards/" rel="nofollow">article</a> from 2013 : </p>
<blockquote>
<p>Before you start hammering that “add to shopping cart” button, note
that the general impression around the web seems to be that the
Leonardo still has a few bugs that need ironing out, and isn’t quite
as beginner friendly as the Uno. For builders already familiar with
Arduino, this is the better deal.</p>
</blockquote>
<p>The question is if Leonardo is still buggy and may cause any confusion to newbie Arduino programmers. Furthermore, Leonardo doesn't have removable chip, so how can one transfer the project into a separate processor and use Arduino to the other project?</p>
|
<blockquote>
<p>The question is if Leonardo is still buggy </p>
</blockquote>
<p>Probably.</p>
<blockquote>
<p>and may cause any confusion to newbie Arduino programmers. </p>
</blockquote>
<p>Definitely. The whole way the Leonardo works is very different to the likes of the Uno. Transitioning from one to the other, if you don't know what the differences really mean, can be confusing.</p>
<blockquote>
<p>Furthermore, Leonardo doesn't have removable chip, so how can one transfer the project into a separate processor and use Arduino to the other project?</p>
</blockquote>
<p>You build your circuit on a PCB and you provide an ICSP header. ICSP stands for <em>I</em>n <em>C</em>ircuit <em>S</em>erial <em>P</em>rogramming. You then use a hardware programmer to install either the Leonardo bootloader, which can then be used to install sketches through USB, or install a sketch direct without the bootloader.</p>
<p>Or, if you're making thousands of them you send your code to Atmel and they burn it to the chip in the factory for you - at a price of course.</p>
|
17580
|
|arduino-uno|
|
what is the difference between providing 7 volts or 12 volts to arduino uno?
|
2015-11-07T21:02:55.253
|
<p>according to <a href="https://www.arduino.cc/en/Main/ArduinoBoardUno" rel="nofollow">this</a> the recommended input voltage is between 7 and 12 volts.<br>
The question is what is the difference between providing 7 volts(minimum recommended volts) and 12 volts(maximum recommended volts) ?.</p>
|
<p>The amount of heat dissipated by the voltage regulator. The higher the voltage you supply the hotter the regulator will get.</p>
|
17585
|
|serial|atmega328|avrdude|avr-gcc|
|
Why atmega168/328p starts to reset?
|
2015-11-08T00:05:04.780
|
<p>First we set fuse bits:</p>
<pre><code>avrdude -c usbasp -p atmega328p -U lfuse:w:0xFF:m -U hfuse:w:0xDF:m -U efuse:w:0x07:m # same for atmega168
</code></pre>
<p>In the following examples we use the following commands to compile and burn all the programs:</p>
<pre><code>avr-gcc -Os -mmcu=atmega328p -c -o serial.o serial.c
avr-ld -o serial.elf serial.o
avr-objcopy -O ihex serial.elf serial.hex
avrdude -c usbasp -p atmega328p -U flash:w:serial.hex
</code></pre>
<p>Let us burn the following program:</p>
<pre><code>#define F_CPU 16000000UL
#include <avr/io.h>
void main (void) {
DDRB |= (1<<PB5);
PORTB |= (1<<PB5);
while (1);
}
</code></pre>
<p>It makes the led to be on constantly. And it stays so for infinite period of time.</p>
<p>Then we burn the following program:</p>
<pre><code>#define F_CPU 16000000UL
#define BAUD 9600
#include <avr/io.h>
char data = 0;
void main(void) {
// Initialize USART:
#include <util/setbaud.h>
UBRR0H = UBRRH_VALUE; // set the speed (Higher bit)
UBRR0L = UBRRL_VALUE; // set the speed (Lower bit)
UCSR0B |= (1<<RXEN0); // enable receiver
UCSR0C |= (1<<UCSZ01)|(1<<UCSZ00); // set mode (8N1)
DDRB |= (1<<PB5); // enable output on pin PB5 (default led on arduino)
while(1) {
while(!(UCSR0A&(1<<RXC0))); // wait until a byte is received
data = UDR0; // read it
if (data) PORTB |= (1<<PB5); // set the led on
}
}
</code></pre>
<p>Then we open a terminal (9600,8N1) and press several keys, until the led turns off.
Now we burn the first program again and the led is constantly blinking. The reason for this is that watchdog times gets started when we press the keys in terminal. But why and when WDT gets started? How to make so that it will not start?</p>
<p>It should be noted also that we can disable the blinking only with complete poweroff/poweron - only after that the led lights constantly without blinking, as necessary.</p>
<p>This happens on atmega168 and atmega328p, 100% reproducible.</p>
<p>avr-gcc version 4.8.1 avrdude version 6.1</p>
<p><strong>NOTE:</strong> bootloader is not used at all.</p>
|
<p>One thing that I found whilst experimenting with command line compilation is that for some strange reason no startup code was being linked with my code, so it all went completely screwy.</p>
<p>I finally tracked the problem down to a missing command line flag while linking.</p>
<p>First, you need to link with <code>avr-gcc</code> not <code>avr-ld</code>. Second, you need to pass the <code>-mmcu=atmega328p</code> flag to the link command so that it knows which startup code to link in.</p>
<p>This is my complete command line sequence for compiling a simple blink program:</p>
<pre><code>avr-gcc -g -mmcu=atmega328p -ffunction-sections -fdata-sections -c -o blink.o blink.c
avr-gcc -mmcu=atmega328p -Wl,--gc-sections -o blink.elf blink.o
avr-objdump -S blink.elf > blink.dis
avr-objcopy -O ihex -R .eeprom blink.elf blink.hex
</code></pre>
<p>You notice I'm making function and data sections too, and then garbage collecting the unused ones - good practice since it can very much reduce the size of your finished program.</p>
<p>I am doing this through a Makefile, which looks like this:</p>
<pre><code>PREFIX=avr-
CC=${PREFIX}gcc
CXX=${PREFIX}g++
LD=${PREFIX}ld
AS=${PREFIX}as
OBJCOPY=${PREFIX}objcopy
OBJDUMP=${PREFIX}objdump
BIN=blink
MCU=atmega328p
OBJS=blink.o
CFLAGS=-g -mmcu=${MCU} -ffunction-sections -fdata-sections
CXXFLAGS=-g -mmcu=${MCU} -ffunction-sections -fdata-sections -fno-exceptions
LDFLAGS=-mmcu=${MCU} -Wl,--gc-sections
${BIN}.hex: ${BIN}.elf
${OBJCOPY} -O ihex -R .eeprom $< $@
${BIN}.elf: ${OBJS}
${CC} ${LDFLAGS} -o $@ $?
${OBJDUMP} -S $@ > ${BIN}.dis
install: ${BIN}.hex
avrdude -c usbasp -p ${MCU} -U flash:w:${BIN}.hex -qq
clean:
rm -f *.o *.elf *.hex
fuses:
avrdude -c usbasp -p ${MCU} -U lfuse:w:0xff:m -U hfuse:w:0xd6:m -U efuse:w:0x05:m -qq
</code></pre>
|
17586
|
|sensors|atmega328|algorithm|
|
Algorithm to detect motion using ultrasonic sensor
|
2015-11-08T00:40:39.840
|
<p>I have a PIR sensor which sometimes give false readings and I have added a ultrasonic sensor to compensate for that. I think my algorithm can work, however currently it is very prone to give false positives.</p>
<h2>Algorithm theory</h2>
<p>My idea is to have an arduino which will obtain six samples and wait 25 milliseconds between each sample and then calculate the <a href="http://www.mathsisfun.com/data/standard-deviation.html" rel="nofollow">variance</a>. If the variance exceeds a specific threshold, which I have set to a thousnad, it will send an motion event over the serial bus.</p>
<h2>Problem with the algorithm</h2>
<p>Ultrasonic sensors can give faulty responds which usually isn't hard to detect. My HC-SR04 sensor can only accurately read the distance between 2 cm and 400 cm. All the faulty readings are usually way over 400 cm or lower than 2 cm, therefore if is not within these boundaries a new try will be made to get a value within the boundaries, if it fails for three times it will assume the distance is exactly 400 cm.</p>
<p>It is redundant to wait for more than 23280 µs because 400*29.1*2 is the corresponding microseconds it would take for the distance to be 400 cm. <code>pulseIn</code> has a timeout value which can be used for this.</p>
<p>In theory this sounds great to me but very often this algorithm will erroneously send motion events. My belief for this is that when the ultrasonic sensor transmitts a wave and wait for it come back, <code>pulseIn</code> will timeout and retry and yet again ask the sensor to send a wave. This happens before the first wave has come back thus the distance will be incorrect and vary from time to time making the variance higher than my threshold.</p>
<p>If the distance is much lower than 4 metres my algorithm works very well.</p>
<h2>What I tried</h2>
<p>I figured I might be able to block for some time until the <em>echo</em> pin on the ultrasonic sensor turns low or a time of 100ms has passed. The code hanged and I couldn't communicate with my arduino any more. I can't see the problem with my code to obtain the distance pursuant to the ultrasonic sensor.</p>
<pre><code>for(tries=3;tries;--tries) {
digitalWrite(TRIG_PIN), LOW); // Set trigger pin low.
delayMicroseconds(2); // Let signal settle.
digitalWrite(TRIG_PIN, HIGH); // Set trigger pin high.
delayMicroseconds(10);
digitalWrite(TRIG_PIN, LOW); // Ping has now been sent.
unsigned long duration = pulseIn(ECHO_PIN, HIGH, 23280); // Duration is in microseconds
unsigned long time = micros();
while(!(PINB & 0b00000010)) { // ECHO_PIN is PB1 or digital pin 9
if((micros() - time) >= 100000) {
continue;
}
}
if(duration >= 116L && duration <= 23280L) { // Is duration within boundaries?
return ((float)(duration)/2.0) / 29.1;
}
}
return 400.0f;
</code></pre>
<p>This just blocks my program indefinently and I had to upload a new program removing that code for my arduino to respond again.</p>
<p>So my question boils down to: how can I resolve this issue where my algorithm very frequently sends motion events erroneously? Is there a better way to detect motion with an ultrasonic sensor?</p>
<p>(<strong>EDIT:</strong> I was really tired when I wrote the code above and Majenko corrected me, I changed the code for this</p>
<pre><code>for(tries=3;tries;--tries) {
digitalWrite(TRIG_PIN), LOW); // Set trigger pin low.
delayMicroseconds(2); // Let signal settle.
digitalWrite(TRIG_PIN, HIGH); // Set trigger pin high.
delayMicroseconds(10);
digitalWrite(TRIG_PIN, LOW); // Ping has now been sent.
unsigned long duration = pulseIn(ECHO_PIN, HIGH, 23280); // Duration is in microseconds
unsigned long time = micros();
while(PINB & 0b00000010) { // ECHO_PIN is PB1 or digital pin 9
if((micros() - time) >= 100000) {
goto retry;
}
}
if(duration >= 116L && duration <= 23280L) { // Is duration within boundaries?
return ((float)(duration)/2.0) / 29.1;
}
retry:
continue;
}
return 400.0f;
</code></pre>
|
<p>The main blocking part of your code is this bit:</p>
<pre><code>while(!(PINB & 0b00000010)) { // ECHO_PIN is PB1 or digital pin 9
if((micros() - time) >= 100000) {
continue;
}
}
</code></pre>
<p>That is saying "While the echo pin is low, check the time. If too much time has passed then carry on with the loop".</p>
<p>So basically that will loop until the echo pin goes high, regardless of the time.</p>
<p>The <code>continue</code> command means to jump back to the beginning of the loop that it's in, be that a while, for, or do loop. In this case it jumps back to the beginning of the while loop it's in.</p>
<p>Instead you should consider using <code>break</code>, which means "Terminate this loop and carry on with what comes next". </p>
<hr>
<p>Ultrasound sensing with <code>pulseIn()</code>, while simple to perform is rarely particularly accurate. Any interrupts that occur during the sensing will affect the outcome, and it's only as accurate as the micros() function allows it to be.</p>
<p>If you need a more precise and reliable measurement you should consider using one of the <em>Input Capture</em> modules in the ATMega. I don't know if there is a library to do it off hand, but programming it through the registers shouldn't be that difficult - just read the datasheet to find out how it all works.</p>
<p>Briefly the operation of IC is:</p>
<ol>
<li>Send trigger pulse</li>
<li>Start IC timer counting</li>
<li>Pulse arrives</li>
<li>IC stops counting automatically and interrupt is triggered</li>
<li>Read counter value and convert to microseconds.</li>
<li>Set flag to indicate a result is available</li>
</ol>
<p>The timing source is the main system clock and counting happens in the background completely parallel to the operation of the CPU, so nothing can interrupt it or delay it. Even if the execution of the IC interrupt routine is delayed by another interrupt running the counter value will have already stopped incrementing, so it will have been "captured" and give the correct result every time.</p>
|
17588
|
|arduino-mega|gps|
|
Using GPS Module ET314AC With arduino Mega
|
2015-11-08T02:16:49.340
|
<p>Can I use GPS Module ET314AC with Arduino Mega? Here is the datasheet of ET314AC <a href="https://www.google.com.pk/url?sa=t&rct=j&q=&esrc=s&source=web&cd=4&cad=rja&uact=8&ved=0CC0QFjADahUKEwil6qrq4vnIAhVBhRoKHQePBOM&url=http%3A%2F%2Fwww.szstoton.com%2Fres%2Fstotongps%2Fpdres%2F201203%2F20120320163340251.pdf&usg=AFQjCNFOZ31eexhFJWxNYqHvN-QWt4GoEA" rel="nofollow">ET314AC Datasheet</a></p>
|
<p>yes you can, the datasheet is saying that you can read from a serial port which is what you want to do.</p>
<p>Connecting the serial port to TX and RX pins of the Arduino, ground and power, you should be able to talk to the module.</p>
<p>I cant find a breakboard for this module so I suppose you are going to solder it or you can give us the link where you bought it.</p>
<p>I suggest you to try with TinyGPS library to decode the data, after you are sure that the module is talking to the Arduino correctly.</p>
|
17594
|
|arduino-uno|wires|rgb-led|
|
Unsure how to connect the anode in this circuit
|
2015-11-08T13:27:40.350
|
<p>I am making a game of X and O’s and ran out of pins on the Arduino. After searching on the internet I found out about connecting it in a grid connecting all the anodes in columns and the different colours in rows but I don't know how to connect the anodes so it only turns on only one of the LEDs rather than the other 2 in the grid if they are all connected to ground. The wires I am unsure to connect are the orange ones in the diagram below (bottom left corner). Note the Red on the RGBs are not used so don't need to be connected</p>
<p><a href="https://i.stack.imgur.com/8G5Oq.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/8G5Oq.jpg" alt="enter image description here"></a></p>
|
<p>Firstly, you have made the classic rookie mistake with your circuit regarding your LED current limiting resistors. You have one per LED group instead of one per LED within a group. The arrangement you have at the moment means that <em>at best</em> some LEDs will be dim or not light at all, and <em>at worst</em> will result in LEDs burning out.</p>
<p>There should be a resistor in every red, green and blue wire in your diagram.</p>
<p>As for what to do with the three orange wires (once you have re-arranged the resistors) they connect to three spare IO pins on the Arduino - you then turn each column on or off as you need - only one column is on at a time. If you need more than 20mA for a column (which is highly likely with up to 9 LEDs on at a time) then those lines should be connected to either +5V or GND (depending on if you are common anode or common cathode) via transistors and the transistors should be switched by the IO pins.</p>
|
17602
|
|transistor|
|
Using 5V arduino with 12v solenoid lock
|
2015-11-08T08:04:54.117
|
<p>I wish to use an arduino like <a href="http://www.snapdeal.com/product/arduino-uno-r3-board-with/566147335" rel="nofollow">this</a> with a 12v solenoid lock like <a href="http://www.ebay.in/itm/331401195916?ssPageName=STRK:MEWNX:IT&_trksid=p3984.m1439.l2649" rel="nofollow">this</a>. How can I do this. I am told that using <a href="https://www.sparkpcb.com/development/l293-d-dc-motor-driver-board.html" rel="nofollow">this</a> might work, but I am also thinking I can use a transistor's amlification to do that. Can you tell which one is better and if transistor, how to do that?</p>
|
<p>By sheer luck your lock solenoid looks very similar to <a href="https://www.adafruit.com/products/1512" rel="nofollow noreferrer">this one</a> (similar spec too "Draws 650mA at 12V") and they have a working circuit for it <a href="https://learn.adafruit.com/secret-knock-activated-drawer-lock" rel="nofollow noreferrer">over here</a> so look at that and see what they used to drive it. <a href="https://learn.adafruit.com/secret-knock-activated-drawer-lock/parts-and-tools" rel="nofollow noreferrer">Apparently</a> it's a TIP120, so the peak/draw current is probably higher than that ballpark figure, which I suspect is for the hold.</p>
<p><a href="https://i.stack.imgur.com/5ptTr.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/5ptTr.jpg" alt="enter image description here"></a>
<a href="https://i.stack.imgur.com/PNupP.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/PNupP.jpg" alt="enter image description here"></a></p>
<p>Overengineering the transistor by an order of magnitude or so (for a poorly spec'd solenoid part) ensures it doesn't go pop so easily. Also, a Darlington like TIP120 is very easy to drive from the arduino or some other microcontroller.</p>
<p><a href="https://learn.adafruit.com/remote-controlled-door-lock-using-a-fingerprint-sensor-and-adafruit-io/setting-up-the-electronic-door-lock" rel="nofollow noreferrer">A similar project</a> using the same solenoid lock used an IRLB8721 (power MOSFET) instead, which is even more beefy in terms of load current it can handle.</p>
|
17617
|
|arduino-uno|programming|temperature-sensor|
|
arduino PWM temperature inexpected results
|
2015-11-09T15:19:33.303
|
<p>I am making a system which regulates the temperature of a plate.
using the PID library
I programed the system as followed: </p>
<pre><code>/********************************************************
* PID Basic Example
* Reading analog input 0 to control analog PWM output 5
********************************************************/
#include <PID_v1.h>
#include "math.h"
int val, output2;
//Define Variables we'll be connecting to
double Setpoint, Input, Output;
//Specify the links and initial tuning parameters
PID myPID( &Input, &Output, &Setpoint,0,20,20, DIRECT);
void setup()
{
//initialize the variables we're linked to
Setpoint = 37; //temperature a reguler
//turn the PID on
pinMode(9, OUTPUT);
myPID.SetOutputLimits(-100, 100);
myPID.SetMode(AUTOMATIC);
Serial.begin(57600);
while (!Serial);
}
void loop()
{
// phase haute
//delay(100-output2);
val = analogRead(1);
float mv = ( val/1024.0)*5000;
Input = mv/10;
myPID.Compute();
{ output2 = map(Output, -100, 100, 0, 200);
Serial.print("output is :");
Serial.println(output2);
digitalWrite(9,HIGH);
delay(output2);
// phase basse
digitalWrite(9,LOW);
}
//analogWrite(5,Output);
//Serial.print("input temperature is :");
//Serial.println(Input);
// Serial.println(Output);
// Serial.println(Input);
}
</code></pre>
<p>As you can see in the code the output result is between 0 and 100.
the temperature desired in the plate is 37 degre. and the actual temperature is 24 degre. consequently, the program supposes to set the value of the output to the max value to reach to 37 degre.
But the problem is my output is setting to different values as you can see here: <a href="https://i.stack.imgur.com/yVt8T.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/yVt8T.png" alt="enter image description here"></a></p>
<p>what can be the problem here ? thank you in advance</p>
|
<p>As Gerben said in a comment, you should add the value of Input to the serial print, to facilitate problem diagnosis. As your question stands, one can only speculate about what the problem might be. My speculation is that the system is unable to cope with parameters (Kp, Ki, Kd) = (0, 20, 20), ie, that it's unstable and unresponsive without proportional control.</p>
|
17624
|
|power|led|
|
Stop Arduino from powering LED strip when connected to USB
|
2015-11-09T17:25:15.133
|
<p>I have a WS2812B LED strip that is controlled by an Arduino. Normally, both the Arduino and LED strip are powered by the same 5V power supply. The 5V and GND pins of the Arduino and LED strip are connected together. If I want to reprogram the Arduino, I have to disconnect the LED strip or else it might want to try and draw power from my computer's USB.</p>
<p>I have a bunch of (assorted) transistors, (schottky, zener) diodes and resistors. Is there something I can build that will allow the power supply to power both the Arduino and LED strip, while the Arduino's USB can only power the Arduino itself?</p>
<p>I've thought about using a diode between the 5V of the Arduino and 5V of the power supply and using a resistor to pull the 5V terminal of the power supply pin low (when the power supply is not connected) but I'm not sure how stable that will be: once the diode starts conducting the resistor will have no chance to pull the pin low again and I'm not sure if the Arduino will like the voltage drop across the diode.</p>
<p>Obviously the external power would be disconnected before plugging the Arduino into USB. Since the LED strip runs on 5V I can't use the VIN pin.</p>
|
<p>I'd try powering the led strip for the power-supply directly, and the arduino board via a (schottky) diode. </p>
<p>That way the led strip will have no power when only usb is plugged in.</p>
<p>The Arduino won't mind that it receive a bit less that 5v because of the voltage drop of the diode.</p>
<p>The only thing to look out for it sending a 5v signal to a WS2812B chip that has no power. According to the datasheet this is not allowed. </p>
<p>So you either need to buffer the output of the arduino going to the input of the WS2812B (e.g. using some transistors, or a <a href="http://elinux.org/images/6/61/EOMA68-UART-RX-DIODE-PROTECT.png" rel="nofollow">simple pull-up with diode</a>). Or, since you are not hot-plugging the usb, have the 5v from the power supply go (via a resistor) to an input on the arduino, so you can detect this in your setup routine, and have it block the rest of the code, or something.</p>
|
17625
|
|arduino-mega|voltage-level|digital|
|
How to read a higher voltage digital input?
|
2015-11-09T18:04:16.577
|
<p>Lets suppose I have a circuit with a car battery, a switch and a led. The led will turn on when the switch is closed, and turn off if it's not. I want to remove the led from the circuit and put an Arduino in that place to "read" when the circuit is closed or open.</p>
<p>I'm a good programmer, so the code is not the real problem. I only want to know how to do this without damaging the board.</p>
<p>How can I do this?</p>
|
<p>As @Gerben says, voltage dividers are a good place to start. To elaborate on the topic, you can use a combination of voltage dividers, zener diodes and clamping diodes. </p>
<p>This <a href="https://electronics.stackexchange.com/questions/35807/how-would-i-design-a-protection-clipper-circuit-for-adc-input">EE.SE post</a> has some good info about this, related to ADC, but still the same.</p>
<p>First off, a voltage divider circuit is easily found on the internet,</p>
<ol>
<li><a href="https://www.google.com/search?q=voltage+divider&ie=utf-8&oe=utf-8" rel="nofollow noreferrer">Google</a></li>
<li><a href="https://en.wikipedia.org/wiki/Voltage_divider" rel="nofollow noreferrer">Wikipedia</a></li>
</ol>
<p>This circuit from <a href="http://hyperphysics.phy-astr.gsu.edu/hbase/electric/voldiv.html" rel="nofollow noreferrer">Hyperphysics</a> shows the basics:
<a href="https://i.stack.imgur.com/cLmul.gif" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/cLmul.gif" alt="Hyperphysics"></a> </p>
<hr>
<p>To add more protection to this so as not to go over the max I/O voltage of the MCU, you can add a zener diode on the <strong>V<sub>out</sub></strong>.
That would give you something like this(<a href="https://electronics.stackexchange.com/a/48317/46355">Olins</a>): </p>
<p><a href="https://i.stack.imgur.com/CSQ5O.gif" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/CSQ5O.gif" alt="credit to Olin"></a></p>
<p>This will give you the desired range to give legitimate High and Low on an I/O.</p>
<hr>
<p>If you wanted to forgo the voltage divider and zener you can use <a href="https://en.wikipedia.org/wiki/Clamper_%28electronics%29" rel="nofollow noreferrer">clamping diodes</a> to the microcontroller supply voltage Vcc. This will give a range that will not damage the I/O.</p>
<p><img src="https://i.stack.imgur.com/HrneK.png" alt="schematic"></p>
<p><sup><a href="/plugins/schematics?image=http%3a%2f%2fi.stack.imgur.com%2fHrneK.png">simulate this circuit</a> – Schematic created using <a href="https://www.circuitlab.com/" rel="nofollow">CircuitLab</a></sup></p>
<p>The 10k resistor is there to limit the current through the diodes, which are Schottky diodes.</p>
<hr>
<p>Another method, which I have used before and is reliable, is to use a diode and two resistors like below:</p>
<p><img src="https://i.stack.imgur.com/uDj4f.png" alt="enter image description here"></p>
<p>The logic is that, when the input <code>IN</code> is > Vcc(5V) the signal on the I/O <code>_IN</code> will be the voltage of the pull_up resistor <code>R2</code>, if it is low or floating the signal will be low. R1 also gives a known logic state if the input floats.</p>
<p><em>Edit</em>: Changed the image to proper logic flow.</p>
|
17627
|
|arduino-uno|
|
Get csv field values
|
2015-11-09T18:41:05.973
|
<p>I am uploading data using Thingspeak and I would like to get only values stored in a field. Is there any way to get this in a cvs http request?</p>
<p>When you call a cvs http url, you get:</p>
<p><a href="https://i.stack.imgur.com/fuxzu.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/fuxzu.png" alt="enter image description here"></a></p>
<p>What I am trying to get is just the value in field2: 10,10,12,12,16 without the headers.</p>
|
<p>You can use this format to achieve what you described:</p>
<pre><code>http://api.thingspeak.com/channels/(channel_id)/field/(field_id).(format)
</code></pre>
<p>Source: <a href="http://community.thingspeak.com/documentation/api/" rel="nofollow">http://community.thingspeak.com/documentation/api/</a></p>
<p><strong>Edit:</strong> It seems that there are no available options that can do what you want. But, you can tweak the response like in this example:</p>
<pre><code> int i;
String response = "created_at,entry_id,field2 2015-10-22 19:30:00,14878,5";
for (i = response.length()-1; i >= 0 ; i--)
{
if (s.charAt(i) == ',') break;
}
String value = response.substring(i+1);
Serial.println(value); // This will show only 5
</code></pre>
|
17631
|
|arduino-uno|serial|xbee|
|
Help to decode xbee S2 API packet
|
2015-11-09T19:30:52.610
|
<p>I'm new at using Xbee and I would like to get some help on how to interpret API packets. Me setup consists of two arduino unos, two xbee S2, two <a href="http://q.lnwfile.com/_/q/_raw/gn/ta/2w.jpg" rel="nofollow noreferrer">xbee shields</a> and a one magnetometer sensor HMC5883L. The sensor is connected to the arduino via I2C and transmitting the data to the xbee (router) using serial communication. On the other side (coordinator) I'm reading and displaying the data on the serial monitor. I have read the data sheet of the xbee but I still can't figure how to interpret the packet. Here is a screen shot of the values that I'm getting on the serial monitor on the router and the corresponding packets on the coordinator's serial monitor.
<a href="https://i.stack.imgur.com/ugIDP.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ugIDP.jpg" alt="enter image description here"></a></p>
<p>There are four bytes that are changing each time so how can I translate them to an integer value. Any help would be greatly appreciated. </p>
|
<p>You have a bunch of "stuff", followed by the data you sent, followed finally by another bunch of "stuff". I don't know what the "stuff" is, but I can see and decode your data easily enough.</p>
<p>I suspect you transmitted the data using <code>.println(...)</code>. That will send an ASCII representation of the data.</p>
<p>So to take the line: <code>-196.88<CR><LF></code>, if we find the ASCII values and represent them as hexadecimal we have:</p>
<blockquote>
<p>2D,31,39,36,2E,38,38,D,A</p>
</blockquote>
<p>Which I am sure you can find in one of those lines - maybe this one:</p>
<blockquote>
<p>0,15,90,0,13,A2,0,40,C1,A8,2E,98,8D,1,<strong>2D,31,39,36,2E,38,38,D,A</strong>,3B</p>
</blockquote>
<p>So you have 14 bytes defining something interesting about the packet (I'm sure Google can tell you what - source and destination maybe, probably a packet length too), then your data, and finally what looks like it's probably a checksum.</p>
|
17632
|
|electronics|
|
Is it possible to run emulator from IC? and how?
|
2015-11-09T19:46:57.033
|
<p>I have an Emulator and Roms I would like to create a portable device to allow me to connect via RCA to a TV and play. Only I have no prior knowledge of how Integrated Circuits function or what they are capable of. If a IC would work, how does one go about programming one to load up the emulator? What other components aside from RCA and USB would I need? Any direction with this would be great and sorry in case I am not asking the proper questions.</p>
<p>I figured arduino is similar to what I am building in regards to circuitry/ electronics. Thanks in advance. </p>
<p>This is the only bit of information I have found online in 4 days thats not store bought. <a href="http://www.voja.rs/PROJECTS/GAME_HTM/2.%20Hardware.htm#Schema" rel="nofollow">CLICK HERE</a></p>
|
<p>Not a chance, I am afraid. The Arduino cannot do what you think it does.</p>
<p>Yes, you could <em>program</em> the Arduino to act like some of the simple old video games, but there is no way it can run a pre-existing emulator program like your computer can.</p>
<p>You need something more like a Raspberry Pi - in fact there is an interesting project that might be just what you want: <a href="http://blog.petrockblock.com/retropie/" rel="nofollow">RetroPie</a></p>
|
17636
|
|arduino-uno|motor|transistor|
|
Why won't the slide switches control the motor in this 123d simulation?
|
2015-11-09T22:21:56.950
|
<pre><code>int guard = 7;
int switchPin = 6;
int motorPin = 9;
void setup(){
pinMode(guard,INPUT);
pinMode(switchPin,INPUT);
pinMode(motorPin,OUTPUT);
}
void loop(){
if (digitalRead(guard==HIGH)&&digitalRead(switchPin==HIGH)) //&&
{
digitalWrite(motorPin,HIGH);
delay(500);
digitalWrite(motorPin,LOW);
delay(1000);
}
else {
digitalWrite(motorPin,LOW);
}
}
</code></pre>
<p><a href="https://i.stack.imgur.com/GiMXO.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/GiMXO.jpg" alt="123dsimulation image"></a></p>
|
<p>This should be written like this:</p>
<pre><code>if ( digitalRead(guard)==HIGH && digitalRead(switchPin)==HIGH ) {
// Rest of the code..
}
</code></pre>
|
17639
|
|arduino-uno|timers|time|rtc|
|
The difference between "time_t" and "DateTime"
|
2015-11-10T01:26:11.673
|
<p>I've run into an issue trying to combine 2 different Arduino timer projects I've found online. </p>
<p>For both projects I'm using a DS3231 RTC, but have been able use the DS1307 library just fine in my code.</p>
<p>The first set of code I picked up started with:</p>
<pre><code>#include <DS1307RTC.h>
</code></pre>
<p>The second set of code I tried to combine did not have this 'include', but instead used </p>
<pre><code>RTC_DS1307 RTC;
</code></pre>
<p>as found here:</p>
<p><a href="https://learn.adafruit.com/ds1307-real-time-clock-breakout-board-kit/understanding-the-code">https://learn.adafruit.com/ds1307-real-time-clock-breakout-board-kit/understanding-the-code</a></p>
<p>As a novice coder, I'm not really sure what the difference between the above two ways to call this library. But I do know the first way using "include", if I want to access the current time on the RTC I use </p>
<pre><code>RTC.get();
</code></pre>
<p>as opposed to the second method which requires:</p>
<pre><code>RTC.now();
</code></pre>
<p>And while it was easy to find documentation to sync the RTC to computer time over the USB cable using this handy bit of code:</p>
<pre><code>// Notify if the RTC isn't running
if (! RTC.isrunning()) {
Serial.println("RTC is NOT running");
}
// Get time from RTC
DateTime current = RTC.get();
DateTime compiled = DateTime(__DATE__, __TIME__);
if (current.unixtime() < compiled.unixtime()) { //CHECKS AGAINST COMPUTERTIME
Serial.println("RTC is older than compile time! Updating");
RTC.adjust(DateTime(__DATE__, __TIME__)); //UPDATES FROM COMPUTER IF OLD TIME IS OFF
}
</code></pre>
<p>I can find no easy alternative using "#include DS1307RTC" </p>
<p>I first thought that the difference between RTC.now() and RTC.get() was just a matter of word substitution. But later on when I want to use a "time_t" call after initializing with "RTC_DS1307 RTC;"</p>
<pre><code> time_t timeNOW = RTC.now();
</code></pre>
<p>I get the error "cannot convert 'DateTime' to 'time_t {aka long unsigned int}' in initialization"</p>
<p>So I'm assuming one method uses "DateTime" and one method uses "time_t". But I'm not sure if this is the case, and if so, how to convert a "DateTime" value to a "time_t" value.</p>
<p>I have two goals in writing this post.</p>
<p>1- Can someone please explain to me the difference between "#include DS1307RTC.h" and "RTC_DS1307 RTC;" and how it impacts my code.</p>
<p>2- I'd like to stick with using ""RTC_DS1307 RTC;", only because it seems easy to sync my RTC to my computer. But if I do, I get the above error. So can someone please tell me how to convert a "RTC now()" call to a "time_t" value? Or is the issue more complicated than just a mere conversion between data types?</p>
|
<p>A <code>DateTime</code> is a full class with lots of methods to it - a <code>time_t</code> is just an unsigned long.</p>
<p><code>time_t</code> is used to store the number of seconds since the <em>epoch</em> (normally 01/01/1970)</p>
<p>The Arduino <em>Time</em> library returns a <code>time_t</code> to the <code>now()</code> function - but RTCLib return s a DateTime object.</p>
<p>The DateTime object, though, has a <code>unixtime()</code> method which will return a <code>time_t</code> representation of the time stored in the DateTime object.</p>
<p>So you can do:</p>
<pre><code>DateTime dt = RTC.now();
time_t time = dt.unixtime();
</code></pre>
|
17642
|
|serial|c++|lcd|button|debounce|
|
Instead of 1 and 0, make display say On or Off
|
2015-11-10T03:15:59.947
|
<p>So for my project, I am making a button that turns on and off an LED, but also display the state of the led on an LCD and by Serial. But my issue is, I don't want it to just show a 0 or a 1, I want it to say On or Off.</p>
<pre><code>#include <LiquidCrystal.h>
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);
int inPin = 22; // the number of the input pin
int outPin = 13; // the number of the output pin
int state = HIGH; // the current state of the output pin
int reading; // the current reading from the input pin
int previous = LOW; // the previous reading from the input pin
// the follow variables are long's because the time, measured in miliseconds,
// will quickly become a bigger number than can be stored in an int.
long time = 0; // the last time the output pin was toggled
long debounce = 200; // the debounce time, increase if the output flickers
void setup(){
// set up the LCD's number of columns and rows:
lcd.begin(16, 2);
// Print a message to the LCD.
lcd.print("System Activated");
//
lcd.setCursor(0, 1);
lcd.print("Ready...");
pinMode(inPin, INPUT);
pinMode(outPin, OUTPUT);
Serial.begin(9600);
Serial.println("System Activated");
Serial.println("Made by Mateo Holguin");
Serial.println("0 = Light is Off | 1 = Light is On");
Serial.println("=======================================");
}
void loop(){
reading = digitalRead(inPin);
if (reading == HIGH && previous == LOW && millis() - time > debounce) {
Serial.println("Button Switch State Change:");
if (state == HIGH)
state = LOW;
else
state = HIGH;
Serial.println(state);
Serial.println("");
lcd.clear();
lcd.print("State: ");
lcd.print(state);
time = millis();
}
digitalWrite(outPin, state);
previous = reading;
}
</code></pre>
|
<p>Another option: use the "inline" <em>if</em> construct:</p>
<pre><code>lcd.print(state ? F("On") : F("Off"));
</code></pre>
<p>The format is:</p>
<pre><code><if comparison> ? <true result> : <false result>
</code></pre>
<p>Note the use of <code>F(...)</code> to force the strings to stay in flash memory.</p>
|
17651
|
|serial|rs485|
|
RS-232 is a protocol or a cable?
|
2015-11-10T10:17:40.027
|
<p>RS-485 and RS-232 are a type of communication protocol or a type and cable?</p>
<p>I studying these serial communication protocols and each place refers to the RS-232 / RS-485 in different ways. Some articles mention that it is a cable, the other a protocol, so I was in doubt.</p>
|
<p>RS-232 etc mean different things in different contexts. More specifically it is called TIA/EIA-232.</p>
<p>It refers to both the electrical characteristics of an NRZ signalling system, and at the same time it refers to the packet format for the transmission of data through such a system.</p>
<p>It also refers to the connectors that are used with such a system and, by extension, the cables that have those connectors on them.</p>
<blockquote>
<p>The standard defines the electrical characteristics and timing of signals, the meaning of signals, and the physical size and pinout of connectors. The current version of the standard is TIA-232-F Interface Between Data Terminal Equipment and Data Circuit-Terminating Equipment Employing Serial Binary Data Interchange, issued in 1997.</p>
</blockquote>
<p>RS-485, or TIA/EIA-485, in contrast <em>only</em> specifies the electrical characteristics and not the data that is sent down the line. It doesn't specify any connectors to use, nor what format the data should take. For instance you can use RS-232 formatted packets, or you could use a MODBUS-RTU format that uses completely different packets. It only refers to the drivers and voltages used.</p>
<blockquote>
<p>TIA-485-A, also known as ANSI/TIA/EIA-485, TIA/EIA-485, EIA-485 or RS-485, is a standard defining the electrical characteristics of drivers and receivers for use in balanced digital multipoint systems.</p>
</blockquote>
|
17653
|
|arduino-due|eclipse|
|
Arduino Due uploading error using Eclipse plugin "avrdude: stk500_recv(): programmer is not responding"
|
2015-11-10T11:07:15.310
|
<p>I have a Arduino Due that I'm trying to upload a sketch to. I follow the tutorial <a href="http://playground.arduino.cc/Code/Eclipse" rel="nofollow">http://playground.arduino.cc/Code/Eclipse</a> to get the board running with the Eclipse plugin. </p>
<p>However uploading the sketch gives me the error</p>
<pre><code>avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x03
</code></pre>
<p>If I use the Arduino IDE everthing works fine. I'm using Eclipse mars with Arduino 1.6.5</p>
<p>What could have gone wrong?</p>
|
<p>You are using the wrong upload tool.</p>
<p>The due is not using avr dude as upload tool.
You need to use bossac.</p>
<p>If you turn on verbose upload in the arduino ide preferences you will see</p>
<pre><code>...arduino\tools\bossac\1.6.1-arduino/bossac.exe ...
</code></pre>
|
17666
|
|esp8266|
|
ESP 8266 does not respond at all
|
2015-11-10T18:24:37.377
|
<p>I have a ESP8266_01, and I wired up. It does not work for me.</p>
<p>I have connected the ESP to an Arduino Uno. I am using a 5V pin from uP with a 3.3V regulator, and I have a voltage divider between RX(ESP) and TX(uP). And I am sure that the wiring is correct. The thing is, I am not getting anything back from ESP, not even errors. And I tried to use different baudrates as well. There is a blue LED flashing from ESP only when I am using 115200, and red LED lights up constantly at any other baudrate. </p>
<p>What have I done wrong here? </p>
<p>I did 4 hours of research already and don't know what else I can do now.
If you have any idea, please leave me a word.</p>
|
<p>Start by uploading blink sketch to your Arduino then connect it to your ESP8266 like this: TX-TX and RX-RX.</p>
<p>Now open Serial Monitor and send AT command and see if it responds. If so then you can control it using your Arduino by wiring it back to TX-RX and RX-TX.</p>
<p>PS: Don't forget to set the line ending in the Serial Monitor to Newline or Carriage Return.</p>
<p><strong>Edit:</strong> Use this code to connect to ESP8266:</p>
<pre><code>#include <SoftwareSerial.h>
const byte rxPin = 2; // Wire this to Tx Pin of ESP8266
const byte txPin = 3; // Wire this to Rx Pin of ESP8266
// We'll use a software serial interface to connect to ESP8266
SoftwareSerial ESP8266 (rxPin, txPin);
void setup() {
Serial.begin(115200);
ESP8266.begin(115200); // Change this to the baudrate used by ESP8266
delay(1000); // Let the module self-initialize
}
void loop() {
Serial.println("Sending an AT command...");
ESP8266.println("AT");
delay(30);
while (ESP8266.available()){
String inData = ESP8266.readStringUntil('\n');
Serial.println("Got reponse from ESP8266: " + inData);
}
}
</code></pre>
<p>Since the Hardware Serial interface will be busy when connected to Computer, then you have to use another Serial interface to communicate with your ESP8266. In this case, Software Serial comes handy. </p>
|
17675
|
|arduino-uno|led|pins|
|
Uno pin 13 LED mysteriously always ON at 0.14V unless pinMode OUTPUT
|
2015-11-11T01:44:09.753
|
<ul>
<li>I upload a blank sketch: pin 13 LED is on. Why?</li>
<li>I connect pin 13 to GND: it turns off until I remove the connection</li>
<li>I connect multimeter between pin 13 and GND: measures 0.14V and LED turns off until multimeter is removed</li>
<li>I press hard reset: LED blinks a few times, turns off for a second then turns on</li>
<li>I upload a sketch that on setup sets pinMode(13, INPUT): pin 13 LED is on</li>
<li>I upload a sketch that on setup sets pinMode(13, OUTPUT): pin 13 LED is off 0.01V</li>
<li>I upload a Blink example: Everything works fine, LED cycles from 4.84V to 0.01V</li>
</ul>
<p>Why is the LED on unless I set pinMode to output? Have I broken my UNO or is this normal?
I swear it wasn't like this a few days ago.</p>
|
<p>If SCK is set as an input then pin 5 of the op amp goes high (pnp transistor input stage) and the op amp output goes high turning on the LED. </p>
|
17685
|
|transistor|
|
Understanding transistor datasheets
|
2015-11-11T10:57:03.863
|
<p>I'm trying my best to understand and utilise questions that already exist as well as other websites, however I just wanted to check the circuit I've come up with (which is a very simple switch circuit) will work. </p>
<p>I plan on using a <a href="https://www.fairchildsemi.com/datasheets/bd/bd135.pdf" rel="nofollow noreferrer">BD139</a> transistor, although I haven't purchased anything yet, so can change to anything really.</p>
<p>The fans are each 0.09A at 12V. I've calculated that R1 should be 360ohms. The 5V control will be coming from an Arduino. I believe it's within the specs of the transistor. Ic max is 1.5A.</p>
<p>Does the circuit look correct? Are there any changes I should make?</p>
<p><img src="https://i.stack.imgur.com/1CWRD.jpg" alt=""></p>
|
<p>For saturation you should assume h<sub>fe</sub> to be 10. This gives:</p>
<p>(5V − 0.85V) / ((0.09A ⋅ 3) / 10) = 154 Ω</p>
<p>Consider using a 150-220Ω base resistor instead. And since a fan is an inductive load, don't forget the flyback diode from the collector to the +12V rail. A 1N4000 series diode should be fine for this small a load.</p>
|
17693
|
|serial|data-type|
|
Assemble or typecast byte array to float
|
2015-11-11T14:38:33.657
|
<p>The serial port on my Arduino Mega is receiving 3 floats as bytes (total of 12 bytes, 4 per float) over serial. Unfortunately I cannot assemble the 4 Bytes in a float, as the serial monitor only displays</p>
<p><code>0.00</code></p>
<p><code>0.00</code></p>
<p><code>0.00</code> etc. </p>
<p>Here is the code:</p>
<pre><code>void serialEvent2() {
if (Serial2.available() > 11) {
byte yawData[3];
yawData[0] = Serial2.read();
yawData[1] = Serial2.read();
yawData[2] = Serial2.read();
yawData[3] = Serial2.read();
float yawAngle = *((float*)(yawData));
Serial.println(yawAngle);
byte pitchData[3];
pitchData[0] = Serial2.read();
pitchData[1] = Serial2.read();
pitchData[2] = Serial2.read();
pitchData[3] = Serial2.read();
float pitchAngle = *((float*)(pitchData));
byte rollData[3];
rollData[0] = Serial2.read();
rollData[1] = Serial2.read();
rollData[2] = Serial2.read();
rollData[3] = Serial2.read();
float rollAngle = *((float*)(rollData));
}
}
</code></pre>
<p>I made sure the data coming to Serial2 is not <code>0</code>.</p>
<p><strong>UPDATE:</strong> The initial mistake was my byte array not being sized correctly. I fixed it. The values I print are fine until after about a second, they get totally weird. Dropped bits/Bytes maybe? Seems odd because a sample sketch written in Processing works perfectly while taking the exact same input.</p>
<p><a href="https://i.stack.imgur.com/Si6fa.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Si6fa.png" alt="enter image description here"></a></p>
|
<p>What if you write</p>
<pre><code>yawData[3] = Serial2.read();
yawData[2] = Serial2.read();
yawData[1] = Serial2.read();
yawData[0] = Serial2.read();
</code></pre>
<p>i.e. you change the endianness of the representation</p>
|
17701
|
|led|motor|
|
Giving the impression of a dying device - making a vibrating motor slow down and stop
|
2015-11-11T18:34:37.313
|
<p>I'm trying to make a gag gift for a friend. The effect I'm trying to imitate is of a device that starts up for a moment and then putters out like something is wrong.</p>
<p>So I need it to:
1. Vibrate a motor for a second or two.
2. Make the vibration sputter out.
3. Light up an LED behind an error message on a paper screen.</p>
<p>I have very little hands on experience with anything electronic, but I have some programming and I took enough physics to know what a capacitor, etc is.</p>
<p>My questions are whether an Arduino is a good and cost effective way to accomplish this and is there any beginner friendly advice anyone can give me to get this accomplish</p>
|
<p>You can control the motor using PWM (Pulse Width Modulation) and make it run for full, then slowly decrease the speed till stop and after light up the led.
This tutorial from Adafruit could be a good start if you are not familiar with PWM and have also some good advices: <a href="https://learn.adafruit.com/adafruit-arduino-lesson-13-dc-motors/overview" rel="nofollow">https://learn.adafruit.com/adafruit-arduino-lesson-13-dc-motors/overview</a></p>
<p>Please be really careful about the supply source. Motors can easy draw more current then the limited available from the pins of arduino. Maybe a H-bridge could be helpfull here.(take a look at this for example of h-bridge: <a href="https://learn.adafruit.com/adafruit-raspberry-pi-lesson-9-controlling-a-dc-motor/lm293d" rel="nofollow">https://learn.adafruit.com/adafruit-raspberry-pi-lesson-9-controlling-a-dc-motor/lm293d</a> )</p>
|
17709
|
|arduino-uno|serial|sketch|python|
|
Python script to toggle LED's
|
2015-11-11T21:29:43.273
|
<p>I have 8 LED's connected to a shift register on my arduino uno r3. I am trying to write a Python3 script that will prompt a user to select one of the LED's and then prompt to toggle on or off.</p>
<p>Should be pretty basic but I cant seem to get this working.</p>
<p>I have already botched my code trying to get this running:</p>
<p>the jist of my python script is</p>
<pre><code>import serial
import os
import time
os.system('clear')
ser = serial.Serial('/dev/cu.usbmodem1431', 9600)
while True:
led = input("Which LED do you wish to operate? (press x to quit): ")
if led >= '0' and led <= '7':
print("Operating LED # %s" % led)
ser.write(str.encode(led)) # sends the choice of led to arduino'
on_or_off = input("Do you want to turn it on or off (press 0 for off and 1 for on): ")
if on_or_off == '0':
#send command to arduino to turn off the selected LED
print("Command sent to arduino to turn OFF LED %s" % led)
ser.write(str.encode(on_or_off))
elif on_or_off == '1':
#send command to arduino to turn on the selected LED
print("Command sent to arduino to turn ON LED %s" % led)
ser.write(str.encode(on_or_off))
else:
print("Please enter 0 or 1 to operate the LED. ")
elif led == 'x':
ser.close()
break
else:
continue
</code></pre>
<p>For some reason Arduino is only dealing with the first input...</p>
<p>HEre is my loop code on the arduino</p>
<pre><code>void loop() {
if(Serial.available() > 0){
led = Serial.read(); // from python script the led to operate
led = led - '0';
if(led >= '0' && led <= '7'){
if(Serial.available() > 0){
ledState = Serial.read(); // expects the led state next
ledState = ledState - '0';
if(ledState == '0'){
shiftWrite(led,LOW);
}else if(ledState == '1'){
shiftWrite(led,HIGH);
}
}
}
}
}
</code></pre>
<p>shiftWrite is a function I wrote because there are 8 LEDS hooked to a shiftRegister</p>
<p><strong><em>update:</em></strong></p>
<p>I tried the state machine suggestion and it didnt work...</p>
<pre><code> void loop() {
while(Serial.available()){
led = Serial.read();
led = led - '0';
if(led>= 0 && led <= 7){
state = 1; //We've received the LED # go to state 1
Serial.println(led);
Serial.println(state);
Serial.println(ledState);
continue;
}
if(state == 1){
ledState = Serial.read();
ledState = ledState - '0';
if(ledState == '0'){
shiftWrite(led,LOW);
}else if(ledState == '1'){
shiftWrite(led,HIGH);
}
state = 0; //Ended the operation return to state 0
}
}
}
</code></pre>
<p>With the serial monitor in the arduino IDE open (not running the python script) I tried this input: 4,1</p>
<p>This is my output on the serial monitor:</p>
<pre><code>4
1
0
1
1
0
</code></pre>
<p>Any ideas? Basically the same problem as before...I actually thought the state machine idea would work...</p>
|
<p>Try this code, it is working as intended:</p>
<pre><code>void setup() {
Serial.begin(9600);
}
int state = 0;
int led;
int ledState;
void loop() {
while (Serial.available())
{
if (state == 0)
{
led = Serial.read() - '0';
if(led >= 0 && led <= 7)
{
state = 1;
Serial.println("Got LED number: " + String(led));
break;
}
}
if (state == 1)
{
ledState = Serial.read() - '0';
if(ledState == 0)
{
Serial.println("LED n " + String(led) + " is now OFF");
}
else if(ledState == 1)
{
Serial.println("LED n " + String(led) + " is now ON");
}
state = 0;
}
}
}
</code></pre>
|
17718
|
|hardware|
|
Arduino Part Needs Identified
|
2015-11-12T03:08:17.397
|
<p><a href="https://i.stack.imgur.com/xCHd9.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/xCHd9.jpg" alt="I do not know what part this is. I ordered an Arduino beginners kit and this part was not labeled. Please help! "></a></p>
<p>I do not know what part this is. I ordered an Arduino beginners kit and this part was not labeled. Please help! </p>
|
<p>It seems that it is an MPU6050 Module 3 Axis Accelerometer Gyroscope Module for Arduino.</p>
<p>Learn more: <a href="http://playground.arduino.cc/Main/MPU-6050" rel="nofollow noreferrer">http://playground.arduino.cc/Main/MPU-6050</a></p>
<p><a href="https://i.stack.imgur.com/epV69.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/epV69.jpg" alt="enter image description here"></a></p>
|
17721
|
|arduino-uno|shields|arduino-nano|spi|
|
How to connect MCP4141 digipot and a data logger shield to the same Arduino board
|
2015-11-12T12:05:25.933
|
<p>The main problem here is that they both need to communicate via the Arduino's SPI bus, and I know that each of the two devices will need its own CS pin (The data logger is hard wired to 10, so the digital potentiometer will need a different one)</p>
<p>This would be fine, except that the digital potentiometer has one pin for both SPI and SDO.
I read that to connect this to the Arduino, the shared pin on the digipot needs to be connected to the MISI pin on the Arduino (pin 12) and then to bridge the MISO pin to the MOSI pin with a resistor.</p>
<p>Would anyone be able to tell if this will work. I do not want to try connecting the two devices like this just in case it breaks something in the board.</p>
<p>Thanks</p>
|
<p>I have done the same thing in the past for a DS1302 RTC that uses the same communication system. Yes, it works. Will it interfere with the other communication though? Quite possibly. It works fine for <em>half duplex</em> communication, but could cause interference with something else on the bus that is <em>full duplex</em>.</p>
<p>If in doubt, and you're not worried about high speed or high efficiency (you're not changing the potentiometer's value often) then use three other pins and bit-bang your own half duplex serial interface - it's not hard.</p>
|
17723
|
|arduino-uno|interrupt|debugging|resistor|components|
|
Diode lights generate false interruptions
|
2015-11-12T13:08:46.780
|
<p>I have spent quite a considerable time debugging my code that was triggering false interruptions. I have found out that the source of the error were the diode lights (on the picture). I would like to ask if anyone can point me to the possible source of such behaviour.</p>
<p>I will try to explain really briefly what the issue was providing only needed (from my point of view) details. If you would require more - tell me.</p>
<p>So, I have a board that looks like this:
<a href="https://i.stack.imgur.com/SSv38.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/SSv38.png" alt="circuit"></a></p>
<p>You can see two reed switches (close circuit in the presence of a magnet) which leads the <code>INT0</code> (pin 2) and <code>INT1</code> (pin 3) on arduino to trigger an interruption on their <code>RISING</code> behaviour. The pull down resistors are 1kOhm. This cirquit works perfectly. </p>
<p>The original version of this circuit had lights in positions <code>D5-D10</code> and <code>D19-D24</code> (between the reed switches and the connections to the interruptor pins). The lights are these:
<a href="https://i.stack.imgur.com/mhMrqm.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/mhMrqm.jpg" alt="diod lights"></a> </p>
<p>The part of the circuit with the red light (connected to <code>INT1</code>) worked flawlessly, while the circuit with the green light (connected to <code>INT0</code>) every once in a while triggered a false interruption in <code>INT1</code>. The lights, however were always blinking correctly.</p>
<p>I have nearly no experience with circuits and hardware, so a pointer on where to start reading to understand the issue is also welcome. Hope to hear from someone who knows what the cause could have been. I would still like to use the lights somehow, because they give a nice feedback on what is happening to the system.</p>
<p>Thanks!</p>
<p>PS. I do not think the code is necessary here, but I will post it too if you like. I am however quite confident that the bug is not on the software side.</p>
|
<p>Aaaaah, ok, now I see...</p>
<p>You put</p>
<blockquote>
<p>+5V - Reed - LED - input pin - 1k resistor - ground</p>
</blockquote>
<p>right?</p>
<p>If so the problem is that a red led has (usually) a voltage drop of about 1.5V, while the green one has a voltage drop of 1.8V-2.0V. The Atmega 328P has a Vih (i.e. the minimum voltage needed for a reliable high) of 0.6*Vcc, so for a 5V supply this value is 3V.</p>
<p>Consequently with a green LED you will have a value TOO CLOSE to the minimum acceptable value for the input pin. Note that the 2.0V value is an usual one, but different leds have different voltages.</p>
<p>Moreover the so-called high-brightness leds (the ones with a transparent case) have a more-than-3V voltage drop, so if you put for instance a blue led you will never receive a signal.</p>
<p>To solve the problem, you have three solutions:</p>
<p>1) use a (low brightness) red led also for the green path
2) remove the led from that path and drive it directly with the arduino (you will have also the notification that arduino has understood the command)
3) change the path to </p>
<blockquote>
<p>+5V - Reed - input pin - LED - 1k resistor - ground</p>
</blockquote>
<p>(i.e. take the voltage BEFORE the led, not after)</p>
<p>I think it'll work then :)</p>
<p>EDIT: according to the data I found on the internet the red led is usually 1.8V, while the green one is usually 2.1V. This does not change my answer, anyway.</p>
<p>And... You won't "fry" your pins with the 5V you are prividing to the circuit....</p>
|
17725
|
|programming|
|
Problem with for loop
|
2015-11-12T13:51:48.473
|
<p>I'm having trouble with the syntax of code. I want to have the motor turn when the next average the program measures is 100 or more greater than the previous average it measured. I don't know how to write the if statement:</p>
<pre><code>if(average == (average>=100)) {
for(pos = 0; pos <= 120; pos += 1) {
sServo.write(pos);
delay(50);
}
for(pos = 120; pos >= 0; pos -= 1) {
sServo.write(pos);
delay(50);
}
}
</code></pre>
|
<p>The motor should</p>
<blockquote>
<p>turn when the next average the program measures is 100 or more greater than the previous average it measured</p>
</blockquote>
<p>So simply write it:</p>
<pre><code>// Old average is called "average"
// Compute the new average and put it in next_average
if ((next_average - average) >= 100)
{
// Turn the motor
}
average = next_average;
</code></pre>
|
17733
|
|arduino-nano|arduino-micro|virtualwire|
|
433MHz sending not receiving
|
2015-11-12T19:35:46.267
|
<p>I'm trying to send data using <a href="http://www.ebay.com/itm/221524421949" rel="nofollow noreferrer">these</a> cheap parts.
When I check the voltage on the data port of the transmitter, I see what I expect, 1.2 and 0.6 fluctuating while sending.
But when I check the receiver I get 0. I've got 3 of the sets and tried them all. Also tried it with running the transmitter on 11V for some extra power. I've added a LED to the transmitter to see when it transmits and I've added a not-so-good antenna to both while they are only 5cm apart during my tests.</p>
<p>Any advice would be appreciated.</p>
<p><strong>Receiver</strong><br>
FS1000A with a LR433A</p>
<pre><code>#include <VirtualWire.h>
const int led_pin = 6;
//const int transmit_pin = 12;
const int receive_pin = 11;
//const int transmit_en_pin = 3;
void setup()
{
delay(1000);
Serial.begin(9600); // Debugging only
Serial.println("setup");
// Initialise the IO and ISR
//vw_set_tx_pin(transmit_pin);
vw_set_rx_pin(receive_pin);
//vw_set_ptt_pin(transmit_en_pin);
//vw_set_ptt_inverted(true); // Required for DR3100
vw_setup(1000); // Bits per sec
vw_rx_start(); // Start the receiver PLL running
}
void loop()
{
uint8_t buf[VW_MAX_MESSAGE_LEN];
uint8_t buflen = VW_MAX_MESSAGE_LEN;
if (vw_get_message(buf, &buflen)) // Non-blocking
{
int i;
digitalWrite(led_pin, HIGH); // Flash a light to show received good message
// Message with a good checksum received, print it.
Serial.print("Got: ");
for (i = 0; i < buflen; i++)
{
Serial.print(buf[i], HEX);
Serial.print(' ');
}
Serial.println();
digitalWrite(led_pin, LOW);
}
}
</code></pre>
<p><strong>Transmitter</strong></p>
<pre><code>#include <VirtualWire.h>
const int led_pin = 11;
const int transmit_pin = 12;
const int receive_pin = 2;
const int transmit_en_pin = 3;
void setup()
{
// Initialise the IO and ISR
vw_set_tx_pin(transmit_pin);
vw_set_rx_pin(receive_pin);
vw_set_ptt_pin(transmit_en_pin);
vw_set_ptt_inverted(true); // Required for DR3100
vw_setup(1000); // Bits per sec
}
byte count = 1;
void loop()
{
char msg[7] = {'h','e','l','l','o',' ','#'};
Serial.println("sending");
msg[6] = count;
digitalWrite(led_pin, HIGH); // Flash a light to show transmitting
vw_send((uint8_t *)msg, 7);
vw_wait_tx(); // Wait until the whole message is gone
digitalWrite(led_pin, LOW);
delay(1000);
count = count + 1;
}
</code></pre>
<p><a href="https://i.stack.imgur.com/ZLAIw.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ZLAIw.jpg" alt="transmitter"></a>
<a href="https://i.stack.imgur.com/xQiju.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/xQiju.jpg" alt="receiver"></a></p>
|
<p>What I thought was the receiver turned out to be the transmitter. I've earned my noob medal now :)
The chip with the LR433A on it is the sending unit.</p>
<p>The code above and the wiring is all good!</p>
|
17734
|
|arduino-uno|i2c|
|
Can I safely integrate 3,3v sensor with 5v Arduino UNO? How?
|
2015-11-12T21:14:09.683
|
<p>I plan to use <a href="https://www.adafruit.com/products/1356" rel="nofollow">Adafruit's RGB sensor</a> with Arduino working as a RGB controller running on 5V. In my location, <a href="https://www.adafruit.com/products/1334" rel="nofollow">the 5V-compatible version of the sensor</a> is not available.</p>
<p>There is a 3,3V pin on my Arduino board. Can I use it to power the sensor, or will the data pins (which are rated 5V) still burn it? </p>
<p>The TCS34725 chip uses I2C communication, which arguably would still be compatible with the 5V (<a href="http://playground.arduino.cc/Main/I2CBi-directionalLevelShifter" rel="nofollow">http://playground.arduino.cc/Main/I2CBi-directionalLevelShifter</a>)</p>
<p>I am still very new to the electronics, and I don't feel confident enough to build my own level converter, and sadly, no converters advertised on <a href="http://playground.arduino.cc/Main/I2CBi-directionalLevelShifter" rel="nofollow">arduino.cc</a> are available in my country (Poland). </p>
|
<p>If you need I2C the best solution is go for a logic level converter based on BSS138 mosfet or similar. I've used a few and they never let me down. Examples: Sparkfun have this <a href="https://www.sparkfun.com/products/12009" rel="nofollow noreferrer">https://www.sparkfun.com/products/12009</a> and Adafruit <a href="http://www.adafruit.com/products/757" rel="nofollow noreferrer">http://www.adafruit.com/products/757</a></p>
<p><img src="https://cdn.sparkfun.com//assets/parts/8/5/2/2/12009-07.jpg" alt=""></p>
<p>if you have also a few transistors available, you can make your own homemade solution till you get something more robust, according to arduino page: <a href="https://playground.arduino.cc/Main/I2CBi-directionalLevelShifter" rel="nofollow noreferrer">https://playground.arduino.cc/Main/I2CBi-directionalLevelShifter</a></p>
<p><a href="https://i.stack.imgur.com/Ub5WD.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Ub5WD.png" alt=""></a><br>
<sub>(source: <a href="https://playground.arduino.cc/uploads/Main/i2c-level-shifter-transistors.png" rel="nofollow noreferrer">arduino.cc</a>)</sub> </p>
|
17736
|
|button|keyboard|pointer|struct|
|
sending ctrl-z in a struct?
|
2015-11-12T21:32:40.340
|
<p>I have a set of buttons wired to an arduino leonardo that are meant to send either single keystrokes to a computer "a, b, c..." etc, or a key sequence like ctrl+z (to perform an undo command.) Effectively this is a little usb keyboard with pre defined buttons. The way the struct is now, I can only manage to send one keystroke, never a modifier key+letter like I need. </p>
<p>The full code is listed here under "working code": <a href="https://arduino.stackexchange.com/questions/17453/arduino-sending-keystrokes-via-push-buttons-proper-bouncing-and-manually-settin">Arduino sending keystrokes via push-buttons. Proper bouncing and manually setting buttons?</a></p>
<p>It just debounces the buttons and sends back actions (just single letters right now) using the ones defined in the struct. (thanks very much jwpat7)</p>
<p>The part in question is this</p>
<pre><code>struct ButtonStruct buttons[nSwitches] = {
{0, sw0, 'A'},
{0, sw1, 'B'},
{0, sw2, 'C'},
{0, sw3, 'D'},
{0, sw4, 'E'},
{0, sw5, 'F'},
{0, sw6, 'G'},
{0, sw7, 'H'}};
</code></pre>
<p>I effectively want to replace the 'A' in {0, sw0, 'A'} to something that sends ctrl+z keystroke/keysequence instead of the letter 'A'.</p>
<p>I've tried KEY_LEFT_CTRL, setting a variable like char ctrlKey = KEY_LEFT_CTRL; and trying {0, sw0, ctrlKey, 'z'}, the "substitution" hex here: <a href="http://www.nthelp.com/ascii.htm" rel="nofollow noreferrer">http://www.nthelp.com/ascii.htm</a> and a number of other things. </p>
<p>I've read through a lot and I can't seem to find anything relevant. I've been told it's possible to use pointers to create a key-sequence but a -> operand in there just throws errors. I'm new and I realize I might have a core principal wrong, but isn't there some simple syntax to send a ctrl+z command (and then releasing it obviously) using that space? When I put {0, sw0, KEY_LEFT_CTRL, 'z'} it just reports "Lz", using the last letter in KEY_LEFT_CTRL instead of treating it as a modifier. I'm so confused</p>
<p>(Also right now one press = one character and doesn't continually report like holding down a key on a regular keyboard. I'd like to fix that too but I'd settle for just a bloody ctrl+z at this point.)</p>
<p><strong>EDIT</strong>: Current Code (compiled!)</p>
<pre><code> enum { sw0=2, sw1=3, sw2=4, sw3=5, sw4=6, sw5=7, sw6=8, sw7=9}; // Switchbutton lines
enum { nSwitches=8, bounceMillis=42}; // # of switches; debounce delay
struct ButtonStruct {
unsigned long int bounceEnd; // Debouncing-flag and end-time
// Switch number, press-action, release-action, and prev reading
byte swiNum, swiActP, charMod, swiActR, swiPrev;
};
struct ButtonStruct buttons[nSwitches] = {
{0, sw0, 'z', KEY_LEFT_CTRL},
{0, sw1, 'B'},
{0, sw2, 'C'},
{0, sw3, 'D'},
{0, sw4, 'E'},
{0, sw5, 'F'},
{0, sw6, 'G'},
{0, sw7, 'H'}};
//--------------------------------------------------------
void setup() {
for (int i=0; i<nSwitches; ++i)
pinMode(buttons[i].swiNum, INPUT_PULLUP);
Keyboard.begin();
}
//--------------------------------------------------------
byte readSwitch (byte swiNum) {
// Following inverts the pin reading (assumes pulldown = pressed)
return 1 - digitalRead(swiNum);
}
//--------------------------------------------------------
void doAction(byte swin, char code, char tosend, char chmodi) {
if (chmodi) { // See if modifier needed
Keyboard.press(chmodi);
Keyboard.press(tosend);
delay(100);
Keyboard.releaseAll();
} else {
Keyboard.write(tosend);
}
}
//--------------------------------------------------------
void doButton(byte bn) {
struct ButtonStruct *b = buttons + bn;
if (b->bounceEnd) { // Was button changing?
// It was changing, see if debounce time is done.
if (b->bounceEnd < millis()) {
b->bounceEnd = 0; // Debounce time is done, so clear flag
// See if the change was real, or a glitch
if (readSwitch(b->swiNum) == b->swiPrev) {
// Current reading is same as trigger reading, so do it
if (b->swiPrev) {
doAction(b->swiNum, 'P', b->swiActP, b->charMod);
}
}
}
} else { // It wasn't changing; but see if it's changing now
if (b->swiPrev != readSwitch(b->swiNum)) {
b->swiPrev = readSwitch(b->swiNum);
b->bounceEnd = millis()+bounceMillis; // Set the Debounce flag
}
}
}
//--------------------------------------------------------
long int seconds, prevSec=0;
void loop() {
for (int i=0; i<nSwitches; ++i)
doButton(i);
}
</code></pre>
|
<p><strike>First off, consider trying '\032' or '\x1A' for the ctrl-z. (See, eg, <em><a href="https://stackoverflow.com/q/16132971">How to send ctrl+z in C</a></em> on stackoverflow.)</strike></p>
<p>To send a ctrl-z, use something like:</p>
<pre><code>Keyboard.press(ctrlKey);
Keyboard.press('z');
delay(100);
Keyboard.releaseAll();
</code></pre>
<p>For more examples of using modifier keys, see the <a href="https://www.arduino.cc/en/Reference/KeyboardPress" rel="nofollow noreferrer">KeyboardPress</a> page at arduino.cc, and the example program <code>KeyboardLogout.ino</code>. [To coordinate this with the <code>struct</code> data structure approach, you could use code somewhat like</p>
<pre><code>tosend = b->actionChar1;
if (tosend < ' ') { // See if modifier needed
Keyboard.press(ctrlKey);
Keyboard.press(tosend+96); // or is it 64?
delay(100);
Keyboard.releaseAll();
} else {
Keyboard.write(tosend);
}
</code></pre>
<p>[You'll need to test which offset, 96 or 64, works in the above code; I don't have a Leonardo or similar to run this on, and haven't looked at the Keyboard library source to see how it treats this.] Another way is to add a modifier-byte field in the <code>struct</code>, and issue it if its non-zero.]</p>
<p>Second, suppose the current form of <code>ButtonStruct</code> is analogous to</p>
<pre><code>struct ButtonStruct {
unsigned long int bounceEnd; // Debouncing-flag and end-time
// Switch number, press-action and prev reading
byte swiNum, actionChar1, swiPrev;
};
</code></pre>
<p>where <code>actionChar1</code> is the action character in use now. You could add another byte to the <code>struct</code>, say <code>actionChar2</code>, and after a statement like <code>Keyboard.write(b->actionChar1);</code> add the following:</p>
<pre><code>if (b->actionChar2)
Keyboard.write(b->actionChar2);
</code></pre>
<p>which says to write out <code>actionChar2</code> if it is non-zero.</p>
<p>In some of the questions linked to the previous question, you may see advice that <code>Keyboard.write</code> won't send non-printing characters. I don't know if that's so, but in any case, there are mods available for <code>Keyboard</code> (ie, changes to the library) that allow non-printing characters and special characters to be sent. </p>
<p>Also note, if your program gets close to using all the RAM memory, you may want to keep <code>buttons[]</code> in ProgMem and access it from there so it doesn't need to be copied into RAM. (See the three ProgMem questions that are linked in the top right sidebar <a href="https://arduino.stackexchange.com/q/13545">.</a> <a href="https://arduino.stackexchange.com/q/14250">.</a> <a href="https://arduino.stackexchange.com/q/16012">.</a>) If you change the struct to use strings instead of single chars for its actions, using less RAM will increase in importance.</p>
<p><em>Edit</em> re: “what I don't know how to change ---> {0, sw0, 'A'}”: </p>
<p><code>{0, sw0, 'A'}</code> initializes an element of <code>buttons[]</code>.
In <code>buttons[]</code>, each element is a <code>ButtonStruct</code>, because <code>buttons[]</code> is an array of <code>ButtonStruct</code>s. (For more about structs, see syntax and examples in eg <a href="https://en.wikipedia.org/wiki/Struct_%28C_programming_language%29#Declaration" rel="nofollow noreferrer">Struct (C programming language)</a> in wikipedia.)</p>
<p>You control what information can be in each element of <code>buttons[]</code> by modifying the definition of <code>ButtonStruct</code>. If you need more data items in each <code>buttons[]</code> entry, then add more data items in the definition of <code>ButtonStruct</code>. Likewise for fewer.</p>
<p>After you decide what information you need to have available to process a button press, modify <code>ButtonStruct</code> to contain exactly that information. It may be that some information will apply in some cases but not in all. If so, when you initialize <code>buttons[]</code>, have some value (say 0) that stands for not-used, and fill in not-used spots with that value. </p>
<p>For example, if you need key modifiers (shift, ctrl, alt) add a modifier item to <code>ButtonStruct</code>.</p>
<p>Whenever you change <code>ButtonStruct</code>, you need to change <code>buttons[]</code> initialization to match. For example, if <code>ButtonStruct</code> were to include <a href="https://www.arduino.cc/en/Reference/KeyboardModifiers" rel="nofollow noreferrer">Keyboard Modifiers</a> and looked like</p>
<pre><code>struct ButtonStruct {
// Switch number, press-actions and prev reading
byte swiNum, actionChar, charMod, swiPrev;
unsigned long int bounceEnd; // Debouncing-flag and end-time
};
</code></pre>
<p>[with some items in a different order than before!] your initializer elements in the <code>buttons[]</code> declaration could look like</p>
<pre><code> { sw29, 'Q' },
</code></pre>
<p>where <code>charMod</code>, <code>swiPrev</code>, and <code>bounceEnd</code> are left to default to zero, or like </p>
<pre><code> { sw37, 'R', KEY_LEFT_CTRL},
</code></pre>
<p>where <code>swiPrev</code> and <code>bounceEnd</code> default to zero.</p>
<p>Then, in your button-action code you could say:</p>
<pre><code>tosend = b->actionChar;
chmodi = b->charMod;
if (chmodi) { // See if modifier needed
Keyboard.press(chmodi);
Keyboard.press(tosend);
delay(100);
Keyboard.releaseAll();
} else {
Keyboard.write(tosend);
}
</code></pre>
<p>For those elements of <code>buttons[]</code> where you specified a modifier, the <code>if</code>'s first branch executes, and for those where you didn't, ie, for plain unmodified characters, the second one does.</p>
<p>There are all sorts of variants on these methods. For example, instead of specifying action characters and modifiers in the <code>buttons[]</code> array, you could change it so that you specify function names, or could have several classes of actions. If 80% of the actions were to issue one simple character, make that class 0, so the action class can usually default to 0.</p>
|
17744
|
|motor|pwm|servo|
|
Brushless motor "jiggles"
|
2015-11-13T04:55:57.303
|
<p>When I run my code, the ESC makes some noises, different on the high pulse and low pulse, then it begins to jiggle for a bit when it gets to the loop. Here is the code:</p>
<pre><code>#include <Servo.h>
#define MAX_SIGNAL 2000
#define MIN_SIGNAL 1000
#define MOTOR_PIN 10
Servo motor;
void setup() {
Serial.begin(9600);
Serial.println("Program begin...");
Serial.println("This program will calibrate the ESC.");
motor.attach(MOTOR_PIN);
// Wait for input
while (!Serial.available());
Serial.read();
Serial.println("Now writing maximum output.");
motor.writeMicroseconds(MAX_SIGNAL);
delay(2000);
// Send min output
Serial.println("Sending minimum output");
motor.writeMicroseconds(MIN_SIGNAL);
delay(2000);
}
void loop() {
motor.writeMicroseconds(MAX_SIGNAL);
}
</code></pre>
|
<p>Your code is familiar to the process of calibrating ESC controllers and is common. As your code is correct, we have to look at the connections. How is arduino connected to the ESC controller? can you provide a diagram? Only GND and Pin 10 should be connected. Do not connect the 5V of arduino. Power up the ESC with an external source. I think ESC signal port is Hi impedance so it should be no need for any resistor. Take a look at this site: <a href="http://robots.dacloughb.com/project-2/esc-calibration-programming/" rel="nofollow noreferrer">http://robots.dacloughb.com/project-2/esc-calibration-programming/</a></p>
<p>You can see in that picture ( and the picture on the link provided), only pwm pin and ground are connected to arduino. Show us your connections if things keep going wrong. Also, does your power source provides enough juice to the motor?</p>
|
17745
|
|arduino-uno|motor|temperature-sensor|
|
Can't read from DHT sensor when motor is running
|
2015-11-13T05:57:32.323
|
<p>I've been following <a href="http://www.electroschematics.com/11291/arduino-dht22-am2302-tutorial-library/" rel="nofollow noreferrer">this tutorial</a> and I've run into some weird problems. When my motor starts running, I get "Failed to read from DHT sensor" on my serial window, meaning that readHumidity() and readTemperature() functions are returning NaNs. </p>
<p>This <strong>only</strong> happens while the motor is running. Once I stop the motor even momentarily, the DHT sensor starts working again.</p>
<p>Does anyone know why this is happening? I'm using a genuine UNO and a RHT03 sensor and some 5.9V motor (TD599839).</p>
<p>I've attached a diagram I made of my circuit in fritzing -
<a href="https://i.stack.imgur.com/CI1q2.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/CI1q2.png" alt=""></a></p>
|
<p>The problem may be electrical noise from the motor, or
you may have a wiring problem (an incorrect or intermittent connection).</p>
<ol>
<li><p>Kira San’s comment “try to add a 100nF ceramic capacitor between the motor terminals” is directed toward suppressing electrical motor noise. As brushes make or break connections on a motor's commutator, arcs and sparks can occur. The capacitor will limit voltage rate of change thus suppressing some of that electrical noise.</p></li>
<li><p>CharlieHanson's comment (add a flyback diode across the motor terminals) is partly related to noise suppression but mostly to suppressing high voltage excursion that occurs when you shut off motor power. While the motor is running, the magnetic field in it stores ½ L i² joules of power. When current stops suddenly, those joules of power convert to a high voltage spike. A <a href="https://en.wikipedia.org/wiki/Flyback_diode" rel="nofollow noreferrer">flyback diode</a> acts as a near-short to absorb that spike. The cathode (cross-bar) of the flyback diode attaches to the high side of the motor voltage, as shown in <a href="http://www.electroschematics.com/wp-content/uploads/2015/02/arduino-dht22-circuit.png" rel="nofollow noreferrer">the circuit diagram</a> of the <a href="http://www.electroschematics.com/11291/arduino-dht22-am2302-tutorial-library/" rel="nofollow noreferrer">project you linked to</a> on electroschematics.com.</p></li>
<li><p>Re “you are using a resistor with that LED, yes? I'll overlook the fact that it's the wrong way round in the schematic!”, if the LED is wired backwards as shown in your drawing, it won't turn on – which is a good thing, because without a resistor (say 300-3000 Ω) in series with the LED, enough current may flow to damage the Uno or the LED. Turn the LED around on the schematic (and on your wiring setup if you didn't already), and add a series resistor.</p></li>
</ol>
<p><em>Edit:</em> A comment says, “Don't have a diode either :S Will an LED work instead?”. LEDs typically have rather low reverse-voltage ratings – 4 to 5 volts. You could put two or three in series and if they don't burn up you're ok for this experiment. But in production, don't depend on LEDs as flyback diodes except where it doesn't matter what happens.</p>
<ol start="4">
<li>Gerben's comment, “What is that capacitor doing there? Slow start?” refers to the 100 μF capacitor shown between transistor base and emitter. In conjunction with the 1KΩ resistor from D4, that gives RC=0.1 second, so the transistor will take an appreciable amount of time to turn on. This has a couple of consequences: PWM control may be less effective (at low duty cycles, PWM depends on short, high-current pulses, to overcome stiction etc) and the transistor will run hotter. If it's a big power transistor, ok. If it's a small switching transistor intended for full-on or full-off, no.</li>
</ol>
<p><em>Edit:</em> A comment refers to a <em><a href="http://www.electroschematics.com/9540/arduino-fan-speed-controlled-temperature/" rel="nofollow noreferrer">fan speed controlled temperature</a></em> page at electroschematics.com. That page shows a <a href="http://www.st.com/web/en/resource/technical/document/datasheet/CD00001225.pdf" rel="nofollow noreferrer">BD139 power transistor</a>, and says the 100 μF capacitor between transistor base and emitter eliminates some motor noise. Thus it falls into the “big power transistor, ok” category. Well, more or less ok. A heat sink may be needed on the transistor and the capacitor probably doesn't need to be that big; eg try 10 μF instead of 100.</p>
<ol start="5">
<li>An ordinary 9V battery easily supplies a dozen milliamps, but current draw larger than that quickly depletes it. See eg <a href="http://www.powerstream.com/9V-Alkaline-tests.htm" rel="nofollow noreferrer">9V Alkaline tests</a> at powerstream.com and my answer to a previous question, <em><a href="https://arduino.stackexchange.com/a/9853/3917">Using Arduino Micro With 12V Buzzer</a></em> that's somewhat related. The motor shown (<a href="http://www.precisionmicrodrives.com/admin/a/search?q=124-001" rel="nofollow noreferrer">TD599839</a>) is rated at 35 mA at 5.9 V no-load, so will draw say 50 mA no-load from a 9V battery and will try to draw several times that if loaded; ie it will overstress an ordinary 9V battery. In brief: Use a wall-wart or equivalent, or a big battery, rather than a small 9V battery when running motors.</li>
</ol>
|
17750
|
|attiny|
|
ATTiny 85 analog input pin number problem
|
2015-11-13T11:53:55.507
|
<p>I am using AT Tiny 85 to read voltage from lead acid battery charger while charging. Basically the setup has two 7-segment displays driven by two SIPO shift registers(74ls164n). And used tiny 85's pin 4 (physical pin3) to read voltage. </p>
<p>I tested the code using arduino and finally burned it to AT Tiny 85, it didn't worked, i debugged it for hours, and pulled hair out of my head, tested it on bread board, eventually i changed the port to "A2" from "4" and surprisingly, everything runs as expected.</p>
<p>My question is why this happens? why <code>analogRead(A2)</code> works while <code>analogRead(4)</code> don't. ?</p>
<p>I am using Arduino IDE 1.6.5 with <a href="https://github.com/damellis/attiny" rel="nofollow noreferrer">https://github.com/damellis/attiny</a> (1.0.1 installed from the board manager) .
<a href="https://i.stack.imgur.com/JipV5.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/JipV5.png" alt="datashett from sparkfun:"></a></p>
<p><strong>Full Code:</strong></p>
<pre><code>//// Arduino Uno Pins
//const int data = 8 ; //Tiny pin 3 (Physical 2)
//const int clock = 9 ;//Tiny pin 2 (physical 7)
//const int battery_Sensor = A0; //Tiny pin 4 (physical 3)
//const int charger_ctrl = 5; //Tinypin 1 (physical 6)
// ATTiny 85 Pins
const int data = 3 ;
const int clock = 2 ;
const int battery_Sensor = 4;
const int charger_ctrl = 1;
int outputValue = 0;
int sensorValue = 0;
int voltage_reading = 0;
int msb = 0;
int lsb = 0 ;
// Qo -> 1
// Q1 -> 2
// Q2 -> 4
// Q3 -> 5
// Q4 -> 6
// Q5 -> 7
// Q6 -> 9
// Q7 -> 10
char c_array[10] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9'} ;
int measure_voltage(){
sensorValue = analogRead(battery_Sensor);
return map(sensorValue, 0, 1023, 0, 50);
}
byte seven_segment(char input, bool period){
byte output_byte;
switch (input) {
case '0':
output_byte = B11101110;
break;
case '1':
output_byte = B10000010;
break;
case '2':
output_byte = B11001101;
break;
case '3':
output_byte = B01101101;
break;
case '4':
output_byte = B00101011;
break;
case '5':
output_byte = B01100111;
break;
case '6':
output_byte = B11100111;
break;
case '7':
output_byte = B00101100;
break;
case '8':
output_byte = B11101111;
break;
case '9':
output_byte = B00101111;
break;
default:
output_byte = B00000001;
break;
}
if(period == 1){
output_byte = output_byte ^ B00010000;
}
return output_byte;
}
void setup()
{
pinMode(clock, OUTPUT); // make the clock pin an output
pinMode(data , OUTPUT); // make the data pin an output
pinMode(charger_ctrl, OUTPUT);
pinMode(battery_Sensor, INPUT);
}
void loop() {
voltage_reading = measure_voltage() ; // voltage x 10
msb = voltage_reading/10;
lsb = voltage_reading%10;
shiftOut(data, clock, LSBFIRST, seven_segment(c_array[lsb], 0));// send this binary value to the shift register
shiftOut(data, clock, LSBFIRST, seven_segment(c_array[msb], 1));
delay(1000);
}
</code></pre>
|
<p>See the <a href="https://github.com/damellis/attiny/blob/master/attiny/variants/tiny8/pins_arduino.h#L52" rel="noreferrer">analogPinToChannel</a> function.</p>
<pre><code>static const uint8_t A0 = 6;
static const uint8_t A1 = 7;
static const uint8_t A2 = 8;
static const uint8_t A3 = 9;
...
#define analogPinToChannel(p) ( (p) < 6 ? (p) : (p) - 6 )
</code></pre>
<p>Using <code>A2</code>, which is <code>8</code>, will return <code>2</code> (<code>8-6</code>) from the <code>analogPinToChannel</code> function. </p>
<p>Using <code>4</code> will give <code>4</code>. There is no (useful) analog channel <code>4</code>.</p>
|
17752
|
|arduino-mega|gps|
|
Connect Antenna to GPS Module ET314AC
|
2015-11-13T12:45:08.857
|
<p>How can I connect antenna to GPS Module ET314AC?(it is not on a breakout board). I have an antenna like this one <a href="http://www.aliexpress.com/item/1575-42MHZ-Magnetic-base-GPS-active-Antenna-with-SMA-Plug-connector-for-GPS-receivers-and-Mobile/1531700595.html" rel="nofollow">GPS Active Antenna</a> and Here is the datasheet of ET314AC<a href="https://www.google.com.pk/url?sa=t&rct=j&q=&esrc=s&source=web&cd=4&cad=rja&uact=8&ved=0CC0QFjADahUKEwil6qrq4vnIAhVBhRoKHQePBOM&url=http%3A%2F%2Fwww.szstoton.com%2Fres%2Fstotongps%2Fpdres%2F201203%2F20120320163340251.pdf&usg=AFQjCNFOZ31eexhFJWxNYqHvN-QWt4GoEA" rel="nofollow">ET314AC Datasheet</a>.I want to connect it manually without any connectors or other things in fact I want to cutoff the connector from antenna.</p>
|
<p>Read the datasheet!</p>
<blockquote>
<p><strong>V_ANT_IN</strong></p>
<p>This pin is reserved an external DC power supply for active antenna.
If using 2.85V active antenna, pin 19 has to be connected to pin 20.
If the bias voltage of active isn’t 2.85V,you can input bias voltage of you need to this pin.</p>
</blockquote>
<p>So just wire the antenna to the RF_IN pin and GND, and connect pin 19 to +3.3V (since your antenna is 3.3V not 2.85V).</p>
|
17758
|
|bootloader|
|
Arduino Bootloader availability
|
2015-11-13T16:30:04.637
|
<p>When I look at arduino and arduino-like boards featuring ATMEGA328 chip, I see that they either use a micro controller or a FTDI chip to program the ATMEGA through Arduino board pin 0 and 1.</p>
<p>This only works because there is a bootloader available on the chip. Is the bootloader present by default or do I need to install it.
What I mean is can I just buy 10,000 ATMEGA328 from ATMEL, put them on boards and program them through UART or do I need to first flash them with a bootloader?</p>
|
<p>The bootloader is the feature supplied with the Arduino board, but not a chip itself. If you want to clone Arduino (fully or partially), you will have to burn the bootloader yourself.</p>
|
17762
|
|arduino-ide|uploading|attiny|avrdude|
|
avrdude: verification error, first mismatch at byte 0x0000 : 0x00 != 0x16 using USBasp
|
2015-11-13T19:41:54.370
|
<p>I'm having this strange error, which pops up around 90% of the time. I am trying to program my attiny25 using USBasp and the Arduino IDE / library. Sometimes it works, most times it doesn't.. This error occurs on large sketches as well as new sketches, with just the empty setup() and loop() functions. The error looks quite random to me, because my program just uploaded after trying around 10 times. Compiling goes fine. The error always occurs at byte 0x0000, and always in the format 0x00 != 0x _ _. I have six wires (correctly) connected from the USBasp to the attiny25. I do not use any resistors, capacitors etc.</p>
<p>Could anyone tell me what could possibly cause this error, and what to do to fix it? </p>
|
<p>I had the same issue even with capacitor between Vcc and GND and resistor between RESET and Vcc. Finally, I use 5V Instead of 3.3V to power up my ATTINY and the problem was solved!</p>
|
17766
|
|arduino-uno|i2c|display|
|
How to display variables on 0.96" OLED with u8glib library?
|
2015-11-13T23:22:27.957
|
<p>I have Arduino Uno and 0.96" I2C Oled 4 Pinned display. These are my Arduino codes:</p>
<pre><code>#include "U8glib.h"
U8GLIB_SSD1306_128X64 u8g(U8G_I2C_OPT_NONE); // VDD=5V SCL=A5 SDA=A4
int a = 10;
void setup(void) {
}
void loop(void) {
u8g.setFont(u8g_font_gdr25r);
u8g.drawStr(8, 30, "E");
u8g.setFont(u8g_font_gdr25r);
u8g.drawStr(30, 30,"l");
delay(2000);
// u8g.println(a); //This code raw is not working
// delay(2000);
}
</code></pre>
<p>I am trying to indicate integer type variable is called "a" to the OLED screen, but u8glib library hasn't got </p>
<blockquote>
<p>println( (int) a );</p>
</blockquote>
<p>function to do this. I only see </p>
<blockquote>
<p>u8g.drawStr(); </p>
</blockquote>
<p>function that this can't handle integer variables to the display. How can I do that? </p>
|
<p>Ok, I have found the solution (Thank you @jwpat7) Here is my working code:</p>
<pre><code>#include "U8glib.h"
U8GLIB_SSD1306_128X64 u8g(U8G_I2C_OPT_NONE); // VDD=5V GND=GND SCL=A5 SDA=A4
int a = 0;
void setup() { }
void loop() {
u8g.firstPage();
do {
u8g.setFont(u8g_font_gdr25r);
//u8g.drawStr(8, 30, "Eeee");
char buf[9];
sprintf (buf, "%d", a);
u8g.drawStr(18, 3, buf);
} while( u8g.nextPage() );
delay(200);
}
</code></pre>
|
17774
|
|flash|string|
|
Any way to use F macro with a passed variable?
|
2015-11-14T12:49:12.333
|
<p>I want to know if it's possible to use the F() macro on text that is being passed to a function.</p>
<p>This is an example function:</p>
<pre><code>void displayMenu(const char * txt, byte &var) {
lcd.clear();
lcd.setCursor(0, 0);
lcd.print(txt);
lcd.setCursor(0, 1);
lcd.print(var);
}
</code></pre>
<p>This is how I'm calling the function:</p>
<pre><code>displayMenu("Backlight:", backlight);
</code></pre>
<p>If I didn't separate the repeating code into a separate function, I would've been able to write it out like this:</p>
<pre><code>lcd.clear();
lcd.setCursor(0, 0);
lcd.print(F("Backlight: "));
lcd.setCursor(0, 1);
lcd.print(var);
</code></pre>
<p>If I try to do:</p>
<pre><code>displayMenu(F("Backlight"), backlight);
</code></pre>
<p>it doesn't work. Also if I try to do this in the function:</p>
<pre><code>lcd.print(F(txt));
</code></pre>
<p>that also doesn't work.</p>
<p>I'm just wondering if such a thing is possible.</p>
|
<p>There is a special type for just this occasion - the <code>__FlashStringHelper</code> type.</p>
<pre><code>void displayMenu(const __FlashStringHelper *txt, byte var) {
lcd.clear();
lcd.setCursor(0, 0);
lcd.print(txt);
lcd.setCursor(0, 1);
lcd.print(var);
}
</code></pre>
<p>Note I removed the <code>&</code> from <code>var</code> - you don't want that unless you are passing a complex class or are wanting to modify the contents of <code>var</code> in the function and have it reflected back outside the function. Passing a reference to a byte (<code>&var</code>) requires two bytes of data - just passing the content of a byte only requires one byte of data.</p>
|
17775
|
|pwm|arduino-micro|
|
Arduino Micro tone() PWM Pins
|
2015-11-14T13:21:25.190
|
<p>according to the <a href="https://www.arduino.cc/en/Reference/Tone" rel="nofollow">tone()</a> documentation using tone() interferes with PWM output:</p>
<blockquote>
<p>Use of the tone() function will interfere with PWM output on pins 3 and 11 (on boards other than the Mega). </p>
</blockquote>
<p>On my <strong>Arduino Micro</strong> it seems to interfere with PWM on pin 5. After using tone() the PWM does not seem to work anymore. If I use pin 3,9 instead everything works fine.</p>
<p>So can someone explain why that is happening and if there is a way to circumvent that?</p>
|
<p>The pin 3 and 11 only refers to boards based on the ATMega328. On these boards timer2 is used by tone, disabling PWM on pins 3 and 11. See Majenko answer about timers.</p>
<p>The Micro (ATMega32u4) tone uses timer 3, which is connected to pin 5 only.</p>
<p>So on the Micro, just don't use pin 5 for PWM when using tone.</p>
<p>Secondly don't trust everything on the arduino.cc website. There quite a bit of misinformation on there.</p>
|
17782
|
|c++|debounce|
|
Two commands in Void loop?
|
2015-11-14T20:56:25.390
|
<p>So basically I'm making 2 buttons turn on and off 2 different LEDs using debounce.
I got that settled with one button to turn on and off 1 LED.
But how do I make it so I can use the same lines but obviously different names of pins in Void loop?</p>
<p>So this is the one command line, but how do I make 2 commands with the if statement, may I have an example? Thanks</p>
<pre><code>#include <LiquidCrystal.h>
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);
int inPin = 22; // the number of the input pin
int inPin2 = 26;
int outPin1 = 13; // the number of the output pin
int outPin2 = 6;
int state = LOW; // the current state of the output pin
int reading; // the current reading from the input pin
int reading2;
int previous = HIGH; // the previous reading from the input pin
int previous2 = HIGH;
// the follow variables are long's because the time, measured in miliseconds,
// will quickly become a bigger number than can be stored in an int.
long time = 0; // the last time the output pin was toggled
long debounce = 200; // the debounce time, increase if the output flickers
//===============================================================================================
void doIt(int outPin)
{
Serial.print("Button Switch State Change:");
if (state == HIGH) state = LOW;
else state = HIGH;
Serial.println(state);
lcd.clear();
lcd.print("Zone1|State: ");
lcd.print(state ? F("On") : F("Off"));
Serial.print(state ? F("On") : F("Off"));
digitalWrite(outPin, state);
}
//===============================================================================================
void setup()
{
// set up the LCD's number of columns and rows:
lcd.begin(16, 2);
// Print a message to the LCD.
lcd.print("System Activated");
//
lcd.setCursor(0, 1);
lcd.print("Ready...");
pinMode(inPin, INPUT);
pinMode(outPin1, OUTPUT);
pinMode(inPin2, INPUT);
pinMode(outPin2, OUTPUT);
Serial.begin(9600);
Serial.println("System Activated");
Serial.println("Made by Mateo Holguin");
Serial.println("0 = Light is Off | 1 = Light is On");
Serial.println("=======================================");
}
//===============================================================================================
void loop()
{
reading = digitalRead(inPin);
reading2 = digitalRead(inPin2);
if (reading == HIGH && previous == LOW && millis() - time > debounce) {
doIt(outPin1);
}
else if (reading2 == HIGH && previous2 == LOW && millis() - time > debounce){
doIt(outPin2);
}
previous = reading;
previous2 = reading2;
time = millis();
}
</code></pre>
|
<p><strong>Edit:</strong> Use the code below as it is, it's working for me:</p>
<pre><code>#include <LiquidCrystal.h>
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);
int inPin = 22;
int inPin2 = 26;
int outPin1 = 13;
int outPin2 = 6;
int state1 = HIGH;
int state2 = HIGH;
int reading;
int reading2;
int previous = HIGH;
int previous2 = HIGH;
int debounce = 150; // the debounce time, increase if the output flickers
//===============================================================================================
void doIt(int outPin, int state)
{
Serial.print("Button Switch State Change:");
if (state == HIGH) state = LOW;
else state = HIGH;
Serial.println(state);
lcd.clear();
if (outPin == outPin1)
lcd.print("Zone1|State: ");
else if (outPin == outPin2)
lcd.print("Zone2|State: ");
lcd.print(state ? F("On") : F("Off"));
Serial.print(state ? F("On") : F("Off"));
digitalWrite(outPin, state);
}
//===============================================================================================
void setup()
{
// set up the LCD's number of columns and rows:
lcd.begin(16, 2);
// Print a message to the LCD.
lcd.print("System Activated");
//
lcd.setCursor(0, 1);
lcd.print("Ready...");
pinMode(inPin, INPUT);
pinMode(outPin1, OUTPUT);
pinMode(inPin2, INPUT);
pinMode(outPin2, OUTPUT);
Serial.begin(9600);
Serial.println("System Activated");
Serial.println("Made by Mateo Holguin");
Serial.println("0 = Light is Off | 1 = Light is On");
Serial.println("=======================================");
}
//===============================================================================================
void loop()
{
reading = digitalRead(inPin);
reading2 = digitalRead(inPin2);
delay(debounce);
if (reading == HIGH)
{
state1 = !state1;
doIt(outPin1, state1);
}
else if (reading2 == HIGH){
state2 = !state2;
doIt(outPin2, state2);
}
}
</code></pre>
|
17784
|
|led|hardware|shift-register|max7219|
|
8x8 solenoid matrix
|
2015-11-15T03:02:04.567
|
<p>I've been teaching a blind student how to program and build electronics with Arduino. So far I've substituted LED's with piezo buzzers with excellent results. We are getting to the point where more complicated output is required and braille displays are excessively expensive.
I've found these micro solenoids on eBay.
<a href="https://i.stack.imgur.com/wxNg7.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/wxNg7.jpg" alt="micro solenoids "></a></p>
<p>They are 5 volts and small enough to place on a grid to create display. Could I substitute these on a regular LED grid and run it via conventional shift register or MAX7219 methods?</p>
<p>Here is the link to the <a href="http://m.ebay.com/itm/2pcs-x-DC-5v-6V-inhaled-Type-Push-Pull-Solenoid-Electromagnet-DC-Micro-Solenoid-/331680100757?nav=SEARCH" rel="nofollow noreferrer">micro solenoids</a>.</p>
|
<p>Looking at the description. They have a permanent magnet inside, so they are kind of "latching". So using an H-bridge you can have them move outward or inward.</p>
<p>The only problem will be that a finger will be <strong>pushing</strong> on the shaft. So unpowered, they will move when a finger goes over them. You would have to add some mechanism that moves another pin, and locks it in place. </p>
|
17786
|
|programming|c++|
|
uint8_t * to integer and string
|
2015-11-15T03:43:29.013
|
<p><strong>Convert text array/buffer to integer and string.</strong></p>
<p>hi! i'm sending text to an arduino and the output of that library is a
uint8_t array.</p>
<p>Atm the text send is a number between "0" and "1023"</p>
<pre><code>void something(uint8_t * text){
analogWrite(13,text);// does not work
}
/*
toInt() also not
int() not
atoi() not
invalid conversion from 'uint8_t* {aka unasigned char*}' to 'const char*'
*/
</code></pre>
<p>i need to convert it to an integer or better to a uint16_t. </p>
<p>As i plan to send custom commands in near future it would also be good to know how to convert that array to a string, that i then split/manipulate/parse.. whatever.</p>
<p>i looked in various posts but i couldn't get it to work on that simple example above. i'm new to c++</p>
<p>if it's needed the length is also aviable inside the function.</p>
|
<p>I've converted first four bytes to string, and then to int :</p>
<pre><code>void something(uint8_t * payload){
String str="";
char c;
for(int i=0;i<4;i++)
if (isDigit(c=(char)(*(payload+i))))
str += c;
int Val =str.toInt();
Val=Val>1023?1023:Val;
analogWrite(14,Val);
}
</code></pre>
|
17787
|
|arduino-uno|esp8266|nodemcu|lua|
|
Communication via IP adress with Arduino IDE and ESP8266
|
2015-11-15T05:28:32.613
|
<p>I have two Arduino boards and two ESP8266 modules with the NodeMCU firmware, and I want to make this:
One Aruino will be connected to one module and a vibration sensor, and when this sensor detects some vibration, it will send some data using the ESP8266 module as a server, then, the other Arduino will recieve the data with the other ESP module and display a message to a LCD screen. </p>
<p>I've already programmed the WiFi modules as a server and as a client using NodeMCU firmware and LuaUploader. The issue I have is that I don't know how to make a program in the Arduino IDE that communicate both Arduino boards using the ip adress assigned to both ESP modules, can you help me? Thanks</p>
|
<p>After reviewing your codes, I've rewritten them this way, I didn't get a chance to test them though, so try them and let me know.</p>
<p><strong>Server code: a. Arduino</strong></p>
<pre><code>#include <SoftwareSerial.h>
int ledPin = 13;
int txPin = 2;
int rxPin = 3;
SoftwareSerial wifi(rxPin, txPin);
void setup() {
pinMode(ledPin, OUTPUT);
Serial.begin(115200); // This baudrate is better than 9600
wifi.begin(9600);
wifi.println("dofile('wifiserv.lua')"); // This where it goes
digitalWrite(ledPin, LOW);
delay(2000); // delay is necessary
}
void loop() {
while(wifi.available())
{
digitalWrite(ledPin, HIGH);
String inData = wifi.readStringUntil('\n');
if (inData.startsWith("Server IP: "))
Serial.println(inData); // This is just the Server IP address
else
Serial.println("Got new sensor value: " + inData)
}
digitalWrite(ledPin, LOW); // This means no data is available
}
</code></pre>
<p><strong>Server code: b. ESP8266</strong></p>
<pre><code>uart.setup(0, 9600, 8, 0, 1, 1 )
wifi.setmode(wifi.STATION)
wifi.sta.config("mynet","pass")
print("Server IP: " .. wifi.sta.getip() .. "\n")
srv = net.createServer(net.TCP)
srv:listen(80,function(conn)
conn:on("receive",function(conn, s)
data = s:match("sensor=(%w+)")
data = data + "\n"
uart.write(0, data)
end)
end)
uart.on("data", function(cmd)
-- When ESP8266 receives data from Arduino, it will trigger this event
end, 0)
</code></pre>
<p><strong>Client code: a. Arduino</strong></p>
<pre><code>#include <SoftwareSerial.h>
int ledPin = 13;
int EP = 9;
int txPin = 2;
int rxPin = 3;
int dato = 10;
String ip; // Assign this to your server IP
SoftwareSerial wifi(rxPin, txPin);
void setup()
{
pinMode(ledPin, OUTPUT);
pinMode(EP, INPUT);
Serial.begin(115200);
wifi.begin(9600);
wifi.println("dofile('wificlie.lua')"); // This where it goes
delay(2000); // delay is necessary
}
void loop()
{
long medida = TP_init();
delay(50);
if(medida > 1000)
{
Serial.println(medida);
digitalWrite(ledPin, HIGH);
String cmd = "ip=" + ip + " " + "data=" + String(dato);
Serial.println("Sending: " + cmd);
wifi.println(cmd);
}
else
{
digitalWrite(ledPin, LOW);
}
}
long TP_init()
{
delay(10);
long medida = pulseIn(EP, HIGH);
return medida;
}
</code></pre>
<p><strong>Client code: b. ESP8266</strong></p>
<pre><code>wifi.setmode(wifi.STATION)
wifi.sta.config("mynet","pass")
uart.setup(0, 9600, 8, 0, 1, 1 )
uart.on("data", function(s)
uart.write(0, "GoSending!")
ip = s:match("ip=(%d+.%d+.%d+.%d+)")
data = s:match("data=(%w+)")
conn = net.createConnection(net.TCP, 0)
conn:on("connection", function(c)
print("connected");
conn:connect(80,ip)
conn:send("sensor=" .. data)
uart.write(0, "Data has been sent successfully")
end)
end, 0)
</code></pre>
|
17797
|
|arduino-ide|
|
Arduino IDE, Underlying Code and Libraries
|
2015-11-15T15:38:28.953
|
<p>I'm trying to better understand what is going on behind the Arduino IDE. First off I am no expert in C or writing firmware to boards but do have experience in real development.</p>
<p>I see currently the Arduino IDE is one big vast library we first select our board.
What I don't understand is where are our header files? The source files for the board you select?</p>
<p>Not only that we use a number of functions already detected within the IDE where are these located also is any of this code editable?</p>
<p>I had a look through the Arduino directory and most of this stuff looks like its Java I was hoping for C files. Thanks for any links, help or info anyone can give.</p>
|
<p>Just check the <a href="https://github.com/arduino/Arduino/tree/master/hardware/arduino/avr/cores/arduino" rel="nofollow">source code</a>. Specifically look at <code>Arduino.h</code>, <code>main.cpp</code> and <code>wiring*</code>.</p>
<p>These files should also be present in the Arduino application folder somewhere, but you'll have to go through quite a few subfolders to find them.</p>
<p>The different boards have different .h file that will specify the pin-numbers and other chip specific data.</p>
<p>The "auto detect" functionality is done by <code>keywords.txt</code> files. At least for libraries. That way if you install a new library with keywords.txt file, the library functions-names are recognized. </p>
<p>The processes of taking all these files, and the users code, and compile it all whole story on it's own.</p>
|
17820
|
|i2c|communication|wire-library|
|
I2C between Arduinos without Master
|
2015-11-16T15:10:12.860
|
<p>I am working on a library for some Arduinos that should talk between each other.
The aim is that I can load the same binaries onto each Arduino. The I2C ID will be set by DipSwitches.
So far everything works pretty nice but once a while everything gets stuck.</p>
<p>I am not asking you to resolve and debug my code, but I am not sure if i have done something completely wrong:</p>
<p>To make all Arduinos interchangeable I have no Master (<code>Wire.begin()</code>) in my I2C Bus.</p>
<p>I read, that the Master would be responsible for the pulse on the Clock line. As I have no Master in my setup maybe that is the reason for the instability.</p>
<p>Can anyone confirm that connecting some I2C Arduinos without master is something that cannot be done? (or do I have to look for some other reason)</p>
|
<blockquote>
<p>Can anyone confirm that connecting some I2C Arduinos without master is something that cannot be done? (or do I have to look for some other reason)</p>
</blockquote>
<p>There is no master except during transmissions. Thus it is possible to rotate the job of master if you want. You would need some way of deciding when it was a particular board's turn to be master.</p>
<p>I have code <a href="http://www.gammon.com.au/forum/?id=11428&reply=2#reply2" rel="nofollow">here on my RS485 page</a> about how you can set up a rolling master using Serial communications. The same basic idea could be used to make a rolling I2C master.</p>
|
17822
|
|arduino-uno|serial|virtualwire|
|
How does the speed work in VirtualWire Library
|
2015-11-16T16:26:34.367
|
<p>I'm analyzing the VirtualWire library and in it, the send messages are being sent with digitalWrite in the "send" method. However, there is a setup speed function. I'm reading that function and I see a lot of prescalers and TCCR variables. However, I'm not quite sure what these things do. Because, if it uses digitalWrite anyway to send the bits, then really is no intrabit delay, etc. Can someone please clarify this?</p>
<p>Sorry if question is convoluted. Happy to do any clarification. Thank you for all guidance!</p>
<p>EDIT: Also, how do I transmit a block of message. Something greater than a byte? I'm trying to calculate BLER of messages and software serial only transmits 1 byte at a time. While virtualWire uses low-level error detection (and i want to avoid the use of any error detection/correction).</p>
|
<p>I think that is used for receiving. By setting the speed, it knows how often it needs to read the input pin. It does this using timer interrupts, so it will run "in the background" without interfering with the main (loop) code. </p>
<p>The TCCR stuff is the set the interval for the timer interrupt.</p>
|
17833
|
|atmega328|atmega32u4|
|
is it possible to convert a 328 design to use a 32U4?
|
2015-11-17T01:39:09.797
|
<p>I have several projects that use simple 328 based arduinos that I built myself, similar to the familiar "arduino on a breadboard" projects that I'm sure everybody has seen. They have just the bare minimum, no ftdi, etc.</p>
<p>Is it possible to drop in the 32U4 without modifying the circuits, or would I have to do a bunch of work to the circuits to get them to work with the 32U4 chips, and if so what are the general steps?</p>
|
<p>Just had a quick look at the datasheets, and the main difference I see physically is the 32u4 is 44 pin package and the 328 is either 32 or 28 pin.
Also the 32U4 seems to have a lot more peripherals.</p>
<p>So based on that yes you will have to modify your circuit. Atmel are fairly consistant with ports and what their alternate functions are though.</p>
<p>eg SPI on portB, uart on portD</p>
<p>But you are just going to have to compare the pinouts on the datasheets see how they differ. And adjust pin connections accordingly.</p>
<p>Datasheets are easy to find. Good Luck!</p>
|
17835
|
|arduino-nano|clones|
|
Why are Arduino clones cheap?
|
2015-11-17T04:50:34.730
|
<p>You can buy Arduino Nano v3 clones from Alibaba at the cost of roughly $2-$3.</p>
<p>I have calculated the cost for fabricating and all the parts in the BOM for Arduino Nano V3, and it ended up costing around $10 to $12 (depending on where you fabricate the board, buy the components and purchasing volume - assuming less than 100 units). </p>
<p>However, how are Chinese clone manufacturers able to slash the price so much it's only ~1/10 of the BOM cost. </p>
<p>Could it purely be due to economy of scale, lower fixed costs (cheap labor), low quality parts <em>(How do you define <strong>low quality parts</strong>)</em>? Or are there other factors at play as well?</p>
|
<p>All the factors mentioned in the question apply to make the cost so low. However, with an exception or two as noted in the next paragraph, “low quality parts” is not much of a factor, as explained in two paragraphs after that. </p>
<p>Possible low quality parts include the USB mini-B socket, crystals or resonators, and the reset switch. The socket and switch contain metal shapes that can be well made or badly (and more cheaply) made. Those badly made will function but may have shorter lives and higher failure rates. For example, the USB cable fit may be loose, or the switch may fall apart. Crystal or resonator accuracy and stability can be poor while still allowing a Nano clone to appear to function ok.</p>
<p>However, <a href="https://en.wikipedia.org/wiki/Surface-mount_technology" rel="nofollow">SMT (surface mount technology)</a> or SMD (surface mount device) parts on the board cannot be made significantly more cheaply than can good parts. SMD LEDs, resistors, diodes, voltage regulators, and capacitors come off of automated assembly lines with little or no manual intervention. See, eg, <a href="https://en.wikipedia.org/wiki/Ceramic_capacitor#Multi-layer_ceramic_capacitors_.28MLCC.29" rel="nofollow">ceramic capacitor manufacturing</a> at wikipedia. Parts are automatically packaged into sealed reels of parts suitable for use on an automatic pick-and-place machine that populates PCBs. In short, the dozen 0603-size SMD LEDs, resistors, and caps, and the nine other passive or small-scale-integration SMD parts on the board will cost about the same coming off a bad manufacturing line as from a good line, so there is little profit to be made producing bad parts. The 20-odd passive parts probably cost a couple of cents, at manufacturing scale.</p>
<p>Active SMD parts like voltage regulators, the ATmega328P, and the 32U4 or CH340, likewise come off automated manufacturing lines. As these parts are more expensive, there is more economic incentive for cheating, and from time to time fake parts get sold and used. In the past (and perhaps still) there have been manufactories that specialize in removing labeling on the tops of cheap or non-functional chips, and putting accurately detailed fake labels for expensive chips on instead. (<a href="https://www.sparkfun.com/news/395" rel="nofollow">For example,</a> NCP5318 buck regulators relabeled as ATmega328s.) In short, most of the active SMD parts on a Nano either are genuine and work or obvious fakes that don't work and earn their sellers bad reputations or jail. </p>
<p>The CH340g USB-to-serial chip vs. ATmega32U4 USB issue is more complicated. Ie, some may think of the CH340 as a lower quality part than a 32U4. The CH340 may need a different USB driver than the 32U4 and may not support 57600 BPS serial in some cases. <a href="http://kiguino.moos.io/2014/12/31/how-to-use-arduino-nano-mini-pro-with-CH340G-on-mac-osx-yosemite.html" rel="nofollow">1</a>, <a href="http://www.arduinodroid.info/2015/07/ch340g-support.html" rel="nofollow">2</a>. The ATmega32U4 seems to be available on Alibaba for $0.10 to $.20 in moderate quantities. I think the CH340g is made only in China and is somewhat cheaper than the ATmega32U4, so its contribution to the BOM total cost may be a few cents.</p>
<p>The PCB probably costs 5 to 10 cents, and assembly is free except for amortized costs of pick and place machines and an IR reflow system with a conveyor. Boards probably are processed (components placed and soldered automatically) in panels of several dozen units, tested automatically, and then separated for packaging.</p>
<p>Summary: Inexpensive parts and automated processing hold down the per-board costs, moreso than cutting corners on component quality. Corners may get cut on assembly quality and on quality assurance inspections.</p>
|
17853
|
|arduino-uno|serial|library|
|
Serial Communication Problem Using Eclipse
|
2015-11-17T21:48:24.217
|
<p><strong>Please help</strong></p>
<p>I have created an Arduino program that will switch the pins when I send a char. It works fine with serial monitor, but the problems come when I send chars with Eclipse using RXTX serial communication. When I click the button to send the char, at first click it does not switch the Arduino pins; it just senses the Rx and Tx LED but the second time it switches on. But when I tried to switch the second LED it first turns off the first LED although that was not my aim, and then it switches the intended LED. Here is my Arduino code.</p>
<pre><code>const int lamp=2;
const int fan=3;
const int pump=4;
const int fridge=5;
char val;
void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
pinMode(lamp,OUTPUT);
pinMode(fan,OUTPUT);
pinMode(pump,OUTPUT);
pinMode(fridge,OUTPUT);
}
void loop() {
// put your main code here, to run repeatedly:
if(Serial.available()) {
val=Serial.read();
if(val=='a') {
digitalWrite(lamp,HIGH);
Serial.print(val);
delay(100);
} else if(val=='b') {
digitalWrite(lamp,LOW);
Serial.print(val);
delay(100);
} else if(val=='c') {
digitalWrite(fan,HIGH);
Serial.print(val);
delay(100);
} else if(val=='d') {
digitalWrite(fan,LOW);
Serial.print(val);
delay(100);
} else if(val=='e') {
digitalWrite(pump,HIGH);
Serial.print(val);
delay(100);
} else if(val=='f') {
digitalWrite(pump,LOW);
Serial.print(val);
delay(100);
} else if(val=='g') {
digitalWrite(fridge,HIGH);
Serial.print(val);
delay(100);
} else if(val=='h') {
digitalWrite(fridge,LOW);
Serial.print(val);
delay(100);
}
} else {
int sensorValue = analogRead(A0);
Serial.println(sensorValue/10);
delay(100);
}
}
</code></pre>
<p><em>Here is a part of my Java code</em></p>
<pre><code>public boolean identifyport() throws PortInUseException, IOException, TooManyListenersException {
this.setVisible(true);
try {
Enum=CommPortIdentifier.getPortIdentifiers();
while(Enum.hasMoreElements())
portname=(CommPortIdentifier)Enum.nextElement();
if(portname.getPortType()==CommPortIdentifier.PORT_SERIAL)
port=portname.open(this.getClass().getName(), 2000);
serialport=(SerialPort)port;
serialport.setSerialPortParams(9600, SerialPort.DATABITS_8, SerialPort.STOPBITS_2,SerialPort.PARITY_NONE);
input=((CommPort) serialport).getInputStream();
output=((CommPort)serialport).getOutputStream();
serialreader=new BufferedReader(new InputStreamReader(input));
serialport.addEventListener(this);
serialport.notifyOnDataAvailable(true);
progressBar.setBackground(Color.GREEN);
portlist.addItem(portname.getName());
progressBar.setValue(i);
slider_3.setValue(value);
Thread.sleep(1000);
prg();
} catch (UnsupportedCommOperationException e1) {
// TODO Auto-generated catch block
JOptionPane.showMessageDialog(contentPane, "Check USB cable connection", "No port available ", 0);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
JOptionPane.showMessageDialog(null, "Port status", "Please connect the device....!!!!", day, null);
}
return rootPaneCheckingEnabled;
}
@Override public void serialEvent(SerialPortEvent e) {
// TODO Auto-generated method stub
if(e.getEventType()==SerialPortEvent.DATA_AVAILABLE){
try {
serial= serialreader.read();
} catch(Exception e1) {
e1.printStackTrace();
}
}
}
public void writedata(int v1) {
try {
output.write(v1);
output.hashCode();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
*And this is part of the switch button;*
Button button_1 = new Button("switch");
button_1.setFont(new Font("Tahoma", Font.BOLD, 13));
button_1.setBounds(10, 10, 117, 42);
panel_3.add(button_1);
button_1.addActionListener(new ActionListener() {
int count=0;
public void actionPerformed(ActionEvent e) {
writedata(v1);
if(count==0) {
canvas.setBackground(Color.RED);
canvas.setForeground(Color.GREEN);
v1='b';
count++;
} else {
canvas.setBackground(Color.YELLOW);
canvas.setForeground(Color.GREEN);
v1='a';
count--;
}
}
});
</code></pre>
<p>Sorry I can not write everything because there is so much code.</p>
|
<p>Thanks my friends, I had already solved the problem, the problem was this....
I made the method that ran after pressing each button, which sent the data at particular button, it seems the data interfered each other but I do not know why, but I had deleted that method and I used to send data using the object I created at each button.</p>
<pre><code>Button button_1 = new Button("switch");
button_1.setFont(new Font("Tahoma", Font.BOLD, 13));
button_1.setBounds(10, 10, 117, 42);
panel_3.add(button_1);
button_1.addActionListener(new ActionListener() {
int count=0;
public void actionPerformed(ActionEvent e) {
if(count==0){
canvas.setBackground(Color.RED);
canvas.setForeground(Color.GREEN);
char v2 = 'a';
try {
output.write(v2);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
count++;
}
else{
canvas.setBackground(Color.YELLOW);
canvas.setForeground(Color.GREEN);
char v1 = 'b';
try {
output.write(v1);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
count--;
}
}
</code></pre>
<p>Now it worked fine....!!!!.</p>
|
17861
|
|arduino-uno|serial|arduino-mega|android|
|
LED Control through bluetooth
|
2015-11-18T04:40:13.387
|
<p>I have an Android app that sends data to the arduino HC-06. It is however giving me colors i did not send to it. Eg. Red in place of green, white in place of red etc.
Here is a snippet of my android code that sends the data via bluetooth</p>
<pre><code> public void onColorChanged(int color) {
BluetoothV2 bluetooth = new BluetoothV2();
int r,g,b;
r = Color.red(color);
g = Color.green(color);
b = Color.blue(color);
bluetooth.Message(r+","+g+","+b);
}
</code></pre>
<p>Here is a snippet of my arduino code</p>
<pre><code>void loop() {
if(Serial.available()>0){
while(Serial.available()>0){
char inChar = (char)Serial.read();
inputString += inChar;
}
int red = Serial.parseInt();
int green = Serial.parseInt();
int blue = Serial.parseInt();
color(red,green,blue);
inputString = "";
Serial.println("R:"&& red &&"G:"&& green &&"B:"&& blue);
}
}
void color (unsigned char red, unsigned char green, unsigned char blue){
analogWrite(redPin, 255-red);
analogWrite(greenPin, 255-green);
analogWrite(bluePin, 255-blue);
}
</code></pre>
<p>Terminal data</p>
<pre><code> 2,,,,,,,,,,,,,2,,5,,,,,,,,,,,,,,,,,,,,,,,,,02725,1,502725,,,,,,,,,02514,5,602515 ,5,3,,,,,025
</code></pre>
<p>Is the problem how i get the data though Serial.read()? Or what am i missing</p>
|
<pre><code>int firstcomma = inputString.indexOf(',');
int secondcomma = inputString.indexOf(',',firstcomma+1);
String r = inputString.substring(0,firstcomma);
String g = inputString.substring(firstcomma+1,secondcomma);
String b = inputString.substring(secondcomma+1);
red = r.toInt();
green = g.toInt();
blue = b.toInt();
Serial.print("R");
Serial.print(red);
Serial.print("G");
Serial.print(green);
Serial.print("B");
Serial.println(blue);
</code></pre>
<p>This solved my problems.</p>
|
17864
|
|arduino-uno|softwareserial|rf|
|
How to transmit more than 1 byte continually?
|
2015-11-18T05:54:23.570
|
<p>In software serial, the write function only sends 1 byte at a time. Is there someway, some library, that i can send multiple bits/bytes, without stopping (and not using digitalWrite)? i want to be able to transmit at least 16 bits as opposed to just 8. </p>
<p>I know i can send 2 bytes, or even 100 bytes. But the thing i'm trying to do is, implement my own LDPC(error correction) codes on the Arduino. Therefore, i'm taking a lot of channel measurements. One of them is figuring out how the error happens during the delay between the stop bit and the next startbit. Often times, this is were synchronization problems occur. So I'm trying to track this down. Hence why, I need to send more than 8 continuous bits. In software serial, it transmits 8 bits, then transmits the stop bit. then write() restarts on the next call. Instead of this, i just want to send more bits, like 64 bits for instance, and look at the BLER on the received data. (the reason why I'm staying away from hardware serial is because i'm doing this with wireless RF modules) Do you guys have any further info regarding this? I'm very grateful! Thank you so much!</p>
<p>Also, it was suggested that I write my own softwareserial, but that's a pretty daunting task. I would like to avoid it, if i can.</p>
<p><strong>EDIT: Let me show you my data.</strong>
So, I'm constantly transmitting the values; 123,124,125,126. </p>
<pre><code>1111011
1111100
1111101
1111110
</code></pre>
<p>The above 4 lines repeat about 2 times. Then, suddenly, it synchronizes incorrectly, and the following 4 lines are being constantly repeated.</p>
<pre><code>11110101
11111001
11101101
11110001
</code></pre>
<p>It never syncs back to the original 4 transmissions. Now, inside the unsynced block of 4 transmitted bytes, there are fragments of the correct transmission inside. For instance, start from the 2nd bit of the 3rd byte of the correct transmitted byte. Now, if you account for the '0' start bit, and try to matchup the bits, the correct bits are being picked up in the correct order. It's just a problem of what the receiver takes as the startbit. </p>
<p>As i'm typing this edit, i realized something else. What i said in the above paragraph is true, then for the unsynced block, there should be a '0' start bit in front. Now, if the messages match up exactly, and if the 0 start bit that is being transmitted is being treated as a payload, then which 0 is being treated as the startbit, because all the bits between the synced and unsynced data are matched up. However, there should be one missing 0 each time because it's being read as a startbit, not databit. </p>
<p>Sorry if this is convoluted. Happy to clarify any part of it. Thank you so much!!</p>
|
<p>I want to point out here that async serial communications relies on both ends providing a clock (there is no transmitted clock signal). Thus the sender clocks out bits at the "baud rate" (eg. 9600 bits per second) and the receiver clocks them in at the same rate.</p>
<p>With a start bit and 8 data bits therefore you can tolerate some difference in the clocks between sender and receiver (and there will be <em>some</em> difference). Effectively you could probably tolerate around a 10% difference in clock frequencies, as even if they are out by 10% the sample at the receiver will still land inside the data bit of the sender.</p>
<p>Now if you want to transmit 64 bits you have reduced this error margin by a factor of 8. So let's say (ball park) that you can now only tolerate a difference of 1% between sender and receiver.</p>
<p>You now need to be pretty sure that the clocks on the respective boards are pretty accurate. The Uno, for example, has a resonator CSTCE16M0V53-R0 which appears to have a tolerance of 0.5% and a frequency stability of 0.2%.</p>
<p>So, if the sender is running 0.5% slow, and the receiver 0.5% fast, you will almost certainly get errors.</p>
<hr>
<blockquote>
<p>However, when it becomes unsyncde, some new 0 bit should be treated as the startbit, in which case it should not be printed. But i don't see any misisng zero. It's as if the actual data just got shifted.</p>
</blockquote>
<p>How will it get unsynced? I don't think you are following how serial comms works. If you don't have any delay between bytes (or batches of bytes in your case) then it is impossible to resync, because if you miss a start bit, all the following bits will appear valid, they'll just be shifted. This is exactly what you are describing.</p>
<p>Really, to <strong>ensure</strong> syncing you need to have a gap between bytes (or batches-of-bytes in your case) longer than a byte might be, otherwise you can get this mis-sync happening. So if you make your batches longer, the gap has to be longer, effectively removing the slight advantage of larger batches.</p>
<p>Imagine you have an incoming stream of bits on the receiver:</p>
<pre><code>011110101101100011110101101101101100110101100101100110101111001010101110111001010101111
1101001010100101101001010100111011111001000010111100100011011001001001001011001001010
</code></pre>
<p>And imagine that you missed that first start bit. Without a gap between bytes (which would appear as: <code>111111111</code>) you have no way of knowing which is a start bit and which is a data bit. Valid data would have a start bit, so you don't mistake valid data for the inter-byte gap.</p>
<p>In other words, with 8-bit bytes, <strong>data</strong> will always be <code>0xxxxxxxx1</code> and thus a gap of <code>1111111111</code> must be the gap and not data because there is no zero there. But with any shorter gap, and if the receiver samples in the middle of byte, it certainly might think that the next 0 in the stream is a start bit (wrongly).</p>
|
17868
|
|arduino-due|
|
Unable to upload sketch on Mac OSX El Capitan
|
2015-11-18T07:22:44.697
|
<p>I recently dusted off an <em>old</em> Arduino Duemilanove to play with. I can connect it to my Mac laptop with the same USB cable I used previously and I'm able to monitor the serial port and see the output from the last sketch I uploaded (five years ago). Everything is unplugged from the board.</p>
<p>When I try to upload a new sketch, the Arduino IDE gets stuck on <code>Uploading...</code> indefinitely:</p>
<pre><code>Using Port : /dev/cu.usbserial-A800eGZI
Using Programmer : arduino
Overriding Baud Rate : 19200
</code></pre>
<p>The board itself has the green <code>PWR</code> LED and amber <code>TX</code> LED on solid once the currently loaded sketch starts running. Initiating an upload causes the amber <code>L</code> LED to blink three times, then the <code>RX</code> LED blinks twice, and finally the <code>TX</code> LED on solid.</p>
<p>Here is the exact board: <a href="https://www.sparkfun.com/products/retired/666" rel="nofollow">https://www.sparkfun.com/products/retired/666</a></p>
<hr>
<p>My research into this issue produced many suggestions that have not resolved the problem...</p>
<p>I disabled the built-in FTDI driver:</p>
<pre><code>sudo kextunload -b com.apple.driver.AppleUSBFTDI
</code></pre>
<p>And made sure the FTDI driver from ftdichip.com was loaded:</p>
<pre><code>sudo kextload /Library/Extensions/FTDIUSBSerialDriver.kext
</code></pre>
<p>I tried <code>csrutil enable --without kext</code> against my better judgement and saw no change.</p>
<p>I also tried a completely separate machine -- my PC running Windows 10 -- and the upload hung there too.</p>
<p>I have tried timing the upload to coincide with a board reset, hoping to sneak my upload in before the current sketch starts running. I did this <em>a lot</em> and got no satisfaction.</p>
<p>I haven't given up yet; there are too many signs of life to think that it's unrecoverable. I'm looking for more suggestions on how to troubleshoot.</p>
<p>I have already ordered another Arduino -- hopefully I can use it to burn the bootloader on the Duemilanove.</p>
|
<p>The problem was that I selected <code>ATMega168</code> when I should have selected <code>ATMega328</code></p>
<p><a href="https://i.stack.imgur.com/BJkTe.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/BJkTe.jpg" alt="facepalm"></a></p>
|
17874
|
|processing-lang|
|
Problem with analog pins' name when trying to connect Arduino board and Processing
|
2015-11-18T13:26:11.723
|
<p>I am trying to use Processing with Arduino Uno board to read the change of voltage done by a potentiometer. The code is simple:</p>
<pre><code>import processing.serial.*;
import cc.arduino.*;
Serial myport;
Arduino arduino;
color off = color(4, 79, 111);
color on = color(84, 145, 158);
int val=0;
float value=0;
void setup() {
size(600, 600);
println(Arduino.list());
arduino = new Arduino(this, Arduino.list()[0], 57600);
arduino.pinMode(0, Arduino.INPUT);
}
void draw() {
stroke(on);
value = arduino.analogRead(0);
println(value);
ellipse(300,300,value,value);
delay(100);
}
</code></pre>
<p>My question is: For analog pins in Arduino IDE one should type A0, A1, ... but here in Processing IDE it is an error to type so. Is it possible that Processing reads the wrong pin? Because in Serial output I always get zero, however, for the same circuit in Arduino IDE the values change as I turn the potentiometer knob.
Thanks</p>
|
<p>(as suggested in comments to bump it down)</p>
<p>your code works ok with me. I've shorted the 3.3v to analog A0 and your code fluctuates between 679~680 in processing </p>
<p><a href="https://i.stack.imgur.com/cqhhi.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/cqhhi.jpg" alt="screenshot"></a> </p>
<p>If it helps, this is the software versions I'm using: Processing - 3.0.1 Arduino IDE - 1.6.6 Firmata - 2.5.0</p>
|
17891
|
|relay|
|
Not sure if logic analyzer shows an error or perhaps just a 'relay bounce'
|
2015-11-18T21:28:15.813
|
<p>I have an Arduino controlling a relay. I was taking a look at the timings using a logic analyzer and at the onset of the relay switching, it quickly switches again. </p>
<p>This seems to be occurring randomly and I thought it could be highlighting a problem with my code but I wondered if it might just be a 'relay bounce' due to the speed of the switch. I've attached an image below. Any feedback is greatly appreciated. Thanks.</p>
<p><a href="https://i.stack.imgur.com/fKaJ7.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/fKaJ7.png" alt="enter image description here"></a></p>
|
<p>According to your plot, the pulse length is 50 microseconds. Typical mechanical relay switching time is 10 milliseconds, which is 200 times longer. It's next to impossible that the pulse is due to your software powering the relay back on for a moment, since the relay simply could not react to such a short input pulse.</p>
<p>So yeah, it's just a bounce. You can safely ignore it in most cases, unless you're counting events or doing something similar. In the latter case, there are both hardware and software <a href="https://en.wikipedia.org/wiki/Switch#Contact_bounce" rel="nofollow">debouncing</a> techniques, which share the basic idea of a low-pass filter.</p>
|
17895
|
|programming|web-server|display|
|
Connect Digital monitor to Arduino?
|
2015-11-18T22:39:24.817
|
<p>I need a small display with ~ 5 digits.
The display needs to show number of visits to my site in real-time.</p>
<p>(Every time someone visits it needs to increase by one).</p>
<p>I thought to create an app, that fetches server stats every 10 seconds, and checks new number of visitors.</p>
<p>Do you think it is better to do with Arduino or Raspberry Pi?</p>
<p>Do you know of a digits monitor that can be connected to it?</p>
|
<p>For the complexity of the pulling of the data from a specific API, I would suggest to use i2c screen from adafruit and a python script running on raspberry pi. this will save you time on coding eth interface and just mostly copy and paste some simple code to communicate to the display</p>
<p>This is one module that I used and it is simple to use: <a href="https://www.adafruit.com/products/1270" rel="nofollow">https://www.adafruit.com/products/1270</a></p>
|
17898
|
|arduino-uno|power|
|
On the Uno, why does VIN require 7-12 volts and the USB only 5 volts?
|
2015-11-19T00:38:29.403
|
<p>I'm just wondering why the VIN would require 7-12 volts when the USB port itself only requires 5 volts? What happens if you power an Uno on VIN with 5 volts?</p>
|
<p>USB's Vcc pin is assumed to be a stable, 5v supply, and is directly connected to the 5v bus on the Arduino board with no further regulation. Vin is assumed to be an unknown and unregulated voltage in the range of 7-12 volts. </p>
<p>The 7v minimum is a requirement of the design of the on-board voltage regulator which needs the 2v "head room" to maintain its output at 5v. A 5v power supply could be designed with a larger input range, even including voltages less than 5v, but the simple design used on the board covers a range of sources at a lower cost than a higher-performance power supply.</p>
|
17901
|
|arduino-uno|power|
|
Powering an Arduino UNO through 5V
|
2015-11-19T01:16:13.493
|
<p>I have a bench supply which I can use to power a breadboard at 5 V. Is it a bad idea to power the the Arduino by going directly to the 5 V pin? It sounds like both this method, and the USB are unregulated, so there would be no difference. Is it safe? Are there any caveats to this?</p>
<blockquote>
<p>5V.This pin outputs a regulated 5V from the regulator on the board. The board can be supplied with power either from the DC power jack (7 - 12V), the USB connector (5V), or the VIN pin of the board (7-12V). Supplying voltage via the 5V or 3.3V pins bypasses the regulator, and can damage your board. We don't advise it.</p>
</blockquote>
<p>They say they "don't advise it", but why?</p>
|
<p>They wouldn't advise it because they provide on board regulation. By feeding it directly you're circumventing their own protection. If however, you're providing your own regulated supply there is no reason why you can't supply it directly. </p>
<p>In a perfect environment, USB should already be regulated. However given the cheap imported USB hubs and plug packs that are available on the market, I would certainly argue that a good bench power supply is no problems in this regards.</p>
|
17919
|
|arduino-uno|code-optimization|
|
How do I set a constant in setup() that I can use in loop()?
|
2015-11-19T14:46:57.547
|
<p>I am new with coding, and I was wondering how I could run something once and define it as a constant. Here is my code:</p>
<pre><code>int sensorValue1 = analogRead(A0);
int sensorValue2 = analogRead(A1);
int g0 = 9.81*9.8;
int h1 = 48;
int R = 287.06;
int a = -0.0065;
void setup() {
Serial.begin(9600);
int p1 = (1.09512*sensorValue2-22.105)*133.3225;
int t1 = (-0.08126*sensorValue1+65.6597)*274.15;
}
void loop() {
String t = "Temperature: ";
String tt = " Celsius";
String p = "Preassure: ";
String pp = " Pascal";
float celsius = -0.08126*sensorValue1+65.6597;
float kelvin = celsius*274.15;
float pascal = (1.09512*sensorValue2-22.105)*133.3225;
float height = (t1/a)*((pascal/p1)^((a*R)/g0))-1)+h1;
Serial.println(t+celsius+tt);
Serial.println(p+pascal+pp);
Serial.println(kelvin);
Serial.println( );
Serial.println(height);
delay(1000);
}
</code></pre>
|
<p>You can't, and there's other things wrong with your code.</p>
<pre><code>int sensorValue1 = analogRead(A0);
int sensorValue2 = analogRead(A1);
</code></pre>
<p>Calling functions from the global scope is an incredibly bad idea. Those are run <em>before</em> the board has been properly initialized, and the results you may get from it are not guaranteed in any way, shape, or form. Instead you must call functions like <code>analogRead()</code> from within another function, like <code>setup()</code>, or <code>loop()</code>.</p>
<p>As for <code>const</code> - a <code>const</code> is just that - a constant value that can <strong>never</strong> change. You can only assign a value to it at the moment of creation.</p>
<p>And that means that you can only use it within the <em>scope</em> it was defined within. As you can't do that in the global scope (see above) then you <em>cannot</em> use a constant.</p>
<p>So just use a normal global variable. It will only change when you tell it to change. Using a <code>const</code> only makes sense when you have a <em>numeric literal</em> that you want to refer to by name. Using <code>const</code> doesn't protect the variable from being changed at run-time by memory leaks, etc, it just protects it from attempts to modify it at compile time - and if possible replace it with the numeric literal that it refers to.</p>
<p>So in summary just use:</p>
<pre><code>int sensorValue1;
int sensorValue2;
int p1;
int t1;
void setup() {
sensorValue1 = analogRead(A0);
sensorValue2 = analogRead(A1);
p1 = (1.09512*sensorValue2-22.105)*133.3225;
t1 = (-0.08126*sensorValue1+65.6597)*274.15;
}
... etc ...
</code></pre>
<p><strong>HOWEVER</strong>: Your program methodology is also completely flawed. You read the analog values once, and do calculations with them once, then repeatedly display the same values over and over again.</p>
<p>You <strong>must</strong> perform a <em>new</em> <code>analogRead()</code> of your sensors every iteration of <code>loop()</code> in order to update the values in your variables.</p>
|
17921
|
|arduino-nano|
|
Convert INT to Array of Strings
|
2015-11-19T14:54:58.347
|
<p>My sensor outputs an int. I would like this to be an array of strings so I can send it with my 433MHz transmitter.</p>
<p>Converting an int to a string to an array of strings seems to be extremely complicated. I've tried multiple approaches.</p>
<p>The error is always: </p>
<blockquote>
<p>array must be initialized with a brace-enclosed initializer</p>
</blockquote>
<pre><code>#include <VirtualWire.h>
const int led_pin = 11;
const int transmit_pin = 12;
const int receive_pin = 2;
const int transmit_en_pin = 3;
int mostureSensor = 0;
void setup()
{
// Initialise the IO and ISR
vw_set_tx_pin(transmit_pin);
vw_set_rx_pin(receive_pin);
vw_set_ptt_pin(transmit_en_pin);
vw_set_ptt_inverted(true); // Required for DR3100
vw_setup(1000); // Bits per sec
}
byte count = 1;
void loop()
{
// read the input on analog pin 0:
String sensorValue = String(analogRead(mostureSensor));
char charBuf[7];
char msg[7] = sensorValue.toCharArray(charBuf, 7);
//char msg[7] = {'h','a','l','l','o',' ','#'};
Serial.println("sending");
msg[6] = count;
digitalWrite(led_pin, HIGH); // Flash a light to show transmitting
vw_send((uint8_t *)msg, 7);
vw_wait_tx(); // Wait until the whole message is gone
digitalWrite(led_pin, LOW);
delay(1000);
count = count + 1;
}
</code></pre>
|
<p>toCharArray is a method. It will copy the value from SensorValur to charBuff, it won't return the char array.</p>
<p>Line:</p>
<pre><code> char msg[7] = sensorValue.toCharArray(charBuf, 7);
</code></pre>
<p>Should be:</p>
<pre><code> sensorValue.toCharArray(charBuf, 7);
</code></pre>
<p>charBuf will already have the sensorValue copied.</p>
<p>Check more about "toCharArray" method :</p>
<p><a href="https://www.arduino.cc/en/Reference/StringToCharArray" rel="nofollow">https://www.arduino.cc/en/Reference/StringToCharArray</a></p>
|
17924
|
|arduino-due|sketch|
|
Arduino sketch does not repeat
|
2015-11-19T15:18:37.500
|
<p>I have a Problem with my code.</p>
<p>My Goal is to receive a Ethernet message via UDP and send the message back via CAN.</p>
<p>It works fine but only with the first packet I send. When I send the same packet again there is no Response as you can see in the screenshot.
I´m using the Arduino Due with a Transceiver. The Programm which sends and reads the Messages is Vector Canoe</p>
<pre><code>#include "variant.h"
#include "due_can.h"
#include "Arduino.h"
#include <SPI.h>
#include <Ethernet.h>
#include <EthernetUdp.h>
byte mac[] = {
0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED
};
IPAddress ip(192, 168, 1, 177);
unsigned int localPort = 8888; // local port to listen on
// buffers for receiving and sending data
char packetBuffer[UDP_TX_PACKET_MAX_SIZE]; //buffer to hold incoming packet,
EthernetUDP Udp;
void setup() {
Can0.init(250000);
Serial.begin(9600);
Ethernet.begin(mac, ip);
Udp.begin(localPort);
}
void loop() {
int packetSize = Udp.parsePacket();
Udp.read(packetBuffer,packetSize);
if (packetSize)
{
int Canframestosend= packetSize/8; //Divides the Ethernet packet by 8 to match with CAN packet
int count =0;
int Rest=packetSize%8; //Needed if the Ethernet packetsize isn´t a multiple of 8
for(int j=0;j<=Canframestosend;j++){
CAN_FRAME NewFrame; //CAN frames which are sent
NewFrame.id=0xFA; //ID of the frames
NewFrame.length=8; //Maximum of bytes a Can frame can have
for (int i=0;i<8;i++){
NewFrame.data.byte[i] = packetBuffer[count]; //Write the Ethernet info byte by byte on the CAN frames
count++;
}
if(packetSize<count){
NewFrame.length=Rest; //Shortens the last frame to avoid unnessecary zeros
}
Can0.sendFrame(NewFrame);
}
}
delay(10);
}
</code></pre>
<p>Maybe there is an endless Loop but I don´t know which and why.</p>
<p>Hope anybody can help me with that!
<a href="https://i.stack.imgur.com/sOZGC.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/sOZGC.jpg" alt="enter image description here"></a></p>
|
<p>I'd guess it's in the if(packetsize) logic -- if you get a packetsize of zero, you still try to read into a zero-size buffer and who knows what would happen. Move the read inside the if(){...}</p>
<p>See <a href="https://www.arduino.cc/en/Reference/EthernetUDPRead" rel="nofollow">https://www.arduino.cc/en/Reference/EthernetUDPRead</a> </p>
<p>Also, you want to limit the reading to the UDP_TX_PACKET_MAX_SIZE size of the buffer, not to the size of the packet.</p>
<p>Update: The UDP_TX_PACKET_MAX_SIZE is only used in the user code, and nowhere else within the Ethernet Library. You could use a larger buffer if you need to by defining and allocating a larger buffer and specifying its size in EthernetUDP.read() (see <a href="https://www.arduino.cc/en/Reference/EthernetUDPRead" rel="nofollow">https://www.arduino.cc/en/Reference/EthernetUDPRead</a>).</p>
|
17933
|
|c++|
|
Including Class with .h and .cpp files
|
2015-11-19T18:23:21.720
|
<p>I am trying to use a class in .ino file. The code is:
<br/><br/> .ino file</p>
<pre><code>#include <LED.h>
int Pin1 = 13;
int Pin2 = 12;
int Pin3 = 11;
LED led;
void setup() {
pinMode(Pin1,OUTPUT);
pinMode(Pin2,OUTPUT);
pinMode(Pin3,OUTPUT);
digitalWrite(Pin1,LOW);
digitalWrite(Pin2,LOW);
digitalWrite(Pin3,LOW);
}
void loop() {
led.on(Pin1);
delay(2);
led.on(Pin2);
delay(2);
led.on(Pin3);
delay(2);
}
</code></pre>
<p>.h file</p>
<pre><code>#ifndef LED_h
#define LED_h
class LED{
public:
void on(int);
void off(int);
};
#endif
</code></pre>
<p>.cpp file</p>
<pre><code>#include <stdio.h>
#include <Arduino.h>
#include "LED.h"
void LED::on(int PIN){
digitalWrite(PIN,HIGH);
}
void LED::off(int PIN){
digitalWrite(PIN,LOW);
}
</code></pre>
<p>Arduino compiler picks the object declaration error:</p>
<p>LEDC:6: error: 'LED' does not name a type<br/>
LEDC.ino: In function 'void loop()':<br/>
LEDC:17: error: 'led' was not declared in this scope<br/></p>
<p>How should I declare objects in Arduino then?<br/></p>
<p>The way that I am putting the files in folders is like the attached image:</p>
<p><a href="https://i.stack.imgur.com/aPIEJ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/aPIEJ.png" alt="enter image description here"></a></p>
|
<p>All you need to do is this in the (.ino)</p>
<pre><code>#include <LED.h>
int Pin1 = 13;
int Pin2 = 12;
int Pin3 = 11;
LED led1;
LED led2;
LED led3;
void setup() {
pinMode(Pin1,OUTPUT);
pinMode(Pin2,OUTPUT);
pinMode(Pin3,OUTPUT);
digitalWrite(Pin1,LOW);
digitalWrite(Pin2,LOW);
digitalWrite(Pin3,LOW);
}
void loop() {
led1.on(Pin1);
delay(2);
led2.on(Pin2);
delay(2);
led3.on(Pin3);
delay(2);
}
</code></pre>
|
17938
|
|arduino-uno|atmega328|avrdude|
|
How to flash the "atmega328" with AVRDUDE?
|
2015-11-19T20:35:46.063
|
<p>I have an external device using an <strong>ATmega328</strong>, not a <strong>ATmega328-P</strong> as used by the Arduino Uno.</p>
<p>Now I want to use <strong>AVRDUDE</strong> and an Arduino Uno to flash a hex file on this chip. Therefore I removed the ATmega that came with the Arduino and popped in the one without the "-P".</p>
<p>With the Arduino IDE, it doesn't work, so I tried AVRDUDE:</p>
<pre><code>avrdude -c arduino -P com3 -p ATMEGA328 -b 19200 -U flash:r:sdint.hex:r
</code></pre>
<p>However, I'm doing something wrong here, because it does not work:</p>
<blockquote>
<p>avrdude: stk500_recv(): programmer is not responding<br />
avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x00<br />
avrdude: stk500_recv(): programmer is not responding<br />
avrdude: stk500_getsync() attempt 2 of 10: not in sync: resp=0x00<br />
...</p>
</blockquote>
<p><strong>What commandline should I use to flash an Arduino Uno with an ATmega328?</strong></p>
|
<p>This seems to be quite a common problem, and there are a number of problems, each with their own solution.</p>
<ul>
<li>Make sure you have selected the right chip</li>
<li>Make sure you have selected the right serial port (when you unplug your board, it should disappear).</li>
<li>Make sure you do not have anything plugged in to the tx & rx pins (usually 0 and 1).</li>
<li>Make sure your Atmega chip has a bootloader on it</li>
<li>Try another cable</li>
<li>There may be a problem with your computer - try another computer</li>
<li>If using another helps, try reinstalling the USB serial driver</li>
<li>Try unplugging the Arduino board, holding down the reset switch, then plugging it in (still holding down reset); continue to hold down reset for about 5 seconds.</li>
<li>make sure nothing else is trying to use your serial port</li>
<li>Does your chip have a bootloader? Chips bought as part of an Arduino will, otherwise, it almost certainly doesn't, unless it specifically says (in the description of what you bought).</li>
</ul>
<p>If it does not have a bootloader (or may not have a bootloader) you will need to set this up. You can either use the instructions here: <a href="https://www.arduino.cc/en/Tutorial/ArduinoToBreadboard" rel="nofollow">https://www.arduino.cc/en/Tutorial/ArduinoToBreadboard</a> (which I never got working) or you can use an ICSP like the <a href="http://www.freetronics.com.au/products/usbasp-icsp-programmer-for-avr-arduino#.VlIY_2xifXs" rel="nofollow">http://www.freetronics.com.au/products/usbasp-icsp-programmer-for-avr-arduino#.VlIY_2xifXs</a> (which is what I use) - works great. They can be had for a few dollars from China.</p>
|
17939
|
|arduino-uno|programming|pwm|timers|frequency|
|
Building an adjustable low frequency PWM controller with Arduino
|
2015-11-19T21:36:10.557
|
<p>I am looking for a way to create an adjustable PWM controller capable of modulation frequency from 0-100 (more preferably 0-1000) Hz, duty cycle from 0-100%, and able to accept a voltage range of 5-30V DC. I have looked through Sparkfun and Adafruit for product or PWM shields capable of this and I have yet to find one. Some servo shields can be programmed down to 50Hz and arduino itself can be slowed to like 30Hz using timer0 and timer1 changes. However none of these options make it easy to vary frequency and none of them can accept much more than 6V. </p>
<p>I have searched far and wide and found a few interesting things:</p>
<p>1) <a href="http://www.instructables.com/id/The-ultimate-PWM-driver-for-many-applications/" rel="nofollow">http://www.instructables.com/id/The-ultimate-PWM-driver-for-many-applications/</a><p>
This instructable shows an analog un-sensored PWM driver. It would get the job done here however, I need a way to read my Frequency and Duty Cycle
<p>
2) <a href="https://www.electronicsblog.net/arduino-frequency-counterduty-cycle-meter/" rel="nofollow">https://www.electronicsblog.net/arduino-frequency-counterduty-cycle-meter/</a>
<p>
Here there is a way using pulsein() and other arduino functions to read both frequency and duty cycle as seen above. But then this is also assuming you're PWM voltage is 5V. So maybe you use a 5V regulator on the signal into the arduino? Would something that simple work or would it skew the signal and prevent accurate measurements? </p>
<p>Obviously, if anyone has a better idea I'm open to it. I've been searching for a solution for some time. The trouble really seems to be the low frequency PWM request.</p>
|
<p>Your question is so close to my own project, for a second I thought it was something I posted awhile back, go figure. I don't expect you to gain from my answer, me coming along to find your question some 2 years, 5 months later. It may be of help to others who pass by this way in the future. I am currently working on the exact same variable duty cycle controller and will offer up my findings. </p>
<p>The following programming code is the result of apx. 5 months of study into the Arduino programming as well as a long failing attempt at getting control through a series of 555 timer chip builds. I shit canned the 555 timer chip & Darlington transistor method. I thought it was too crude, and all 'engineering' schematics never allowed me to have anything more than a 50% duty cycle control. I wanted control over all PWM variables. Today I will be purchasing a metal case, or making one that can hold apx. 5-6 potentiometers allowing me to adjust every possible variable within the PWM domain of parameters (there are more variables than what I have in this code below). I will give you some details in the code first, that will give you some idea of the obsessively precise control I'm demanding from my PWM project:</p>
<p>Getting into the heart of the variable HIGH/LOW control. Be sure to read everything you can to understand fully why these functions are needed. Also, know that with 10 bits the 1023 value allows a resolution of .0043 volt increments (really nice):</p>
<pre><code>void loop()
{
Potentiometer1 = analogRead(PotHzHIGH);
Potentiometer1 = map(Potentiometer1, 0, 1023, 1023, 0);
Potentiometer1 = constrain(Potentiometer1, 500, 1023);
Potentiometer2 = analogRead(PotHzLOW);
Potentiometer2 = map(Potentiometer2, 0, 1023, 1023, 0);
Potentiometer2 = constrain(Potentiometer2, 500, 1023);
Potentiometer3 = analogRead(Pot5Volts);
Potentiometer3 = map(Potentiometer3, 0, 1023, 1023, 1023); //Hold at 12Volts
Potentiometer3 = constrain(Potentiometer3, 0, 1023);
//Potentiometer3 can either be locked at 12volts with the map function, or
//you can use a Potentiometer to varry the voltage. I illistrate the
//constant at 12 volts with the map function - low/high both set to
//1023 & 1023
digitalWrite(PotHzHIGH, HIGH);
//turn it ON delayMicroseconds(PotHzHIGH);
//Keep ON for Potentiometer1=PotHzHIGH Microseconds
//1000 microseconds = 1millisecond; 1000ms = 1second
digitalWrite(PotHzLOW, LOW);
//turn it OFF delayMicroseconds(PotHzLOW); //Keep OFF for
Potentiometer2=PotHzLOW Microseconds
//1000 microseconds = 1millisecond; 1000ms = 1second;
//Largest value within the delayMicroseconds function: 16383microseconds
//Largest value when converted to milliseconds is 16.383ms, or axp. 1/20th of
//...a second
</code></pre>
<p>}</p>
<pre><code>//other things to understand about the above program. It is possible to
//have the LOW written with: delayMicroseconds(PotHzLOW+100);
//or delayMicroseconds(PotHzLOW*1.1);
//You can add an additional potentiometer to be the multiplier of the LOW.
//these added controls prevent the LOW from ever being less than the high.
//this can come in handy if you wish to work within duty cycles that are
//between 1% & 50%. It is of interest to me because I am dealing with
//high frequencies.
</code></pre>
<p>timkasey1@gmail.com</p>
|
17940
|
|arduino-uno|led|rgb-led|neopixel|
|
Arduino and WS2812 RGB LED Strip "freezing"
|
2015-11-19T21:39:01.757
|
<p>I have been working on a project as a gift for my girlfriend for Christmas which involves some a bunch of standard "white" LEDs controlled by shift registers and darlington arrays, and also some RGB LED strips (WS2812B strip, 29 LEDs on strip). Everything is going fine with the white LEDs, but not so much with the RGB ones. </p>
<p>If I leave the RGB leds running for a while all of the LEDs on the strip turn red, except for the first one, which continues to change color. I am not sure how long "a while" is because in "short term" testing, approximately running continuously for an hour, it works fine and all of the LEDs change appropriately, but if I leave it running overnight I wake up with the issue of all red and one single RGB "working". I then have to reset to get it working again. These RGB LEDSs need to be run for long periods (24 hours) of time without "freezing". The rest of the program (with the normal LEDs) continues to work fine despite the RGB ones not.</p>
<p>Let me explain how I am controlling them. <code>V_rgb</code> is 5V (5V - 8A power supply), which it is also grounded to. Then the data line, <code>C</code>, is connected to an Arduino Uno, on pin 12, which is a PWM pin. </p>
<p>In software, I am using a Adafruit Neopixel Library to control the RGB LEDs and write their respective colors, based off the examples given in their git repo and the tutorial <a href="http://www.tweaking4all.com/hardware/arduino/arduino-ws2812-led/" rel="nofollow">here</a>.</p>
<p>I have pasted my code below in case that may help, but honestly I am not sure if it is software or hardware related. (unrelated code has been removed)</p>
<pre><code>#include <Adafruit_NeoPixel.h>
#define rgbPin 11
#define numRGBleds 29
Adafruit_NeoPixel strip = Adafruit_NeoPixel(numRGBleds, rgbPin, NEO_GRB + NEO_KHZ800);
int colorStep = 0;
int rgbIndex = 0;
void shiftColor() {
int i = 0;
for (i = 0; i < numRGBleds; i++) {
int idx = (rgbIndex + i) % numRGBleds;
int colorVal = round(i * colorStep);
strip.setPixelColor(idx, Wheel(colorVal & 255));
}
strip.show();
rgbIndex++;
}
uint32_t Wheel(byte WheelPos) {
WheelPos = 255 - WheelPos;
if (WheelPos < 85) {
return strip.Color(255 - WheelPos * 3, 0, WheelPos * 3);
} if (WheelPos < 170) {
WheelPos -= 85;
return strip.Color(0, WheelPos * 3, 255 - WheelPos * 3);
}
WheelPos -= 170;
return strip.Color(WheelPos * 3, 255 - WheelPos * 3, 0);
}
void setup()
{
strip.begin();
strip.show();
rgbIndex = 0;
colorStep = 255 / (numRGBleds - 1);
}
void loop()
{
shiftColor();
delay(1000); // Redo every second
}
</code></pre>
<p>My thoughts of what it could be are the following, let me know if any make any sense or are known issues:</p>
<ul>
<li>Having issues with <code>micros()</code> value rollover</li>
<li>Overheating</li>
<li>Noisy power supply</li>
<li>Defective LED strip</li>
<li>black magic?</li>
</ul>
<p>Thanks in advance for any help. </p>
<p><strong>UPDATE</strong></p>
<p>My current solution to the problem is to just reset the board using the watchdog functionality. It reboots in a few milliseconds and sometimes flashes in the process, but I would like to figure out the real problem. </p>
<p><strong>UPDATE #2</strong> </p>
<p>So with the reset solution, I left it running overnight and it did not freeze which leads me to think it is definitely a software, not hardware, issue. I have changed some of the wiring and coding to make sure the watchdog reset is not noticeable. It resets every half hour or so. This will make sure all of the memory is cleaned, except stuff I store in the EEPROM (which I do use to make the reset less noticeable). This reset delays processing by a few milliseconds, but time is not critical, so it is not a big deal. </p>
<p>I still however, would like to know a more elegant way of doing this. The software reset is a bit "hacky"</p>
|
<p>Try changing <code>rgbIndex++;</code> to <code>rgbIndex=(rgbIndex+1)%numRGBleds;</code>. I thing the problem is the int rgbIndex rollover, which occurs after about 9 hours.</p>
<p>Also try changing delay(1000) to delay(1). That way the problem might pop up a lot faster. </p>
|
17941
|
|arduino-yun|
|
Yun availability
|
2015-11-19T22:49:13.367
|
<p>I am starting a project that may need a lot of Arduino Yuns in the future, but today I found that they are not available on the official Arduino store.</p>
<p>What's the story on the Yun? Is it being replaced by something newer? Also, how can I evaluate the longer-term availability of this board?</p>
<p>In case it's helpful, I need the dual-processor setup, wifi capability, and extra storage of the Yun.</p>
|
<p>In short: Who knows?!</p>
<p>With all the in-fighting between the two Arduino factions (Arduino.cc and Arduino.org) it's anyone's guess what boards are going to be available this time next year, and of those that are available which of the two factions will be producing and distributing them.</p>
|
17946
|
|arduino-uno|led|pwm|analogwrite|
|
Why does an LED sometimes flash when increasing brightness?
|
2015-11-20T03:09:37.380
|
<p>This is admittedly a cross-post from <a href="http://forum.arduino.cc/index.php?topic=360468.0" rel="nofollow">LED fade malfunction (random flash) </a> but I can't get an answer on the Arduino forum.</p>
<p>I was mucking around with some very basic code and I noticed that when repeatedly holding an LED at 0 brightness for 1 second and then fading in to full brightness, a small flash would occasionally happen at the beginning of each fade (seemingly random). </p>
<pre><code>int led = 11;
int brightness = 0;
void setup()
{
pinMode(led, OUTPUT);
}
void loop()
{
if(brightness >= 256) //checks if brightness has passed 255, resets to 0
{
analogWrite(led, 255);
brightness = 0;
}
analogWrite(led, brightness);
if(brightness == 0)
{
delay(1000); //LED off for 1 second
}
brightness+=1; //increment brightness
delay(20);
}
</code></pre>
<p>So, the thing that has me completely perplexed is that I can use a different piece of code (below) and the flash goes away!</p>
<pre><code>int i = 0;
int led = 11;
void setup()
{
pinMode(led,OUTPUT);
}
void loop()
{
analogWrite(led, i);
delay(6);
if(i%256 == 0)
{
i = 0 ;
delay(1000);
}
i++;
}
</code></pre>
<p>Has anyone got any clue as to why this would happen? Both programs have basically the same code, except for that i is reset to 0 in the first program whereas in the second, i keeps incrementing past 255 so that analogWrite 'overflows.' I think it must be a firmware, (or maybe a software?) problem.</p>
<p>There is a video on youtube of it happening here, <a href="https://www.youtube.com/watch?v=mbBJWjYScng" rel="nofollow">Arduino - fading LED problem</a>.</p>
|
<p>According to the links you provide from the arduino.cc forum the question is more or less answered. If not that important, just avoid <code>analogWrite(led,0)</code> and make it <code>analogWrite(led,1)</code></p>
<p>if you still want that <code>analogWrite(led,0)</code>, I've tested your code with the advice and it seems to work OK when changing the register manually:</p>
<pre class="lang-c prettyprint-override"><code>#include "wiring_private.h"
int led = 11;
int brightness = 0;
void setup()
{
pinMode(led, OUTPUT);
}
void loop()
{
if (brightness >= 256) //checks if brightness has passed 255, resets to 0
{
brightness = 0;
sbi(TCCR2A, COM2A1);
OCR2A = 0; // set pwm duty
}
analogWrite(led, brightness);
if (brightness == 0)
{
delay(1000); //LED off for 1 second
}
brightness += 1; //increment brightness
delay(20);
}
</code></pre>
<h1>Edit: to explain what those "strange codes" are</h1>
<p>I'm not very expert in this field to explain how exactly this works but basically <code>sbi</code> is function defined in a macro by Atmel (?), it stands for "<strong>s</strong>et <strong>b</strong>it <strong>i</strong>n" and is used to change registers of ATmega chips. So basically what I did was change register defined by the macro <code>TCCR2A</code> (why? because it is the register that controls PWM in pin 11) and pass the bitmask <code>COM2A1</code> (this is a mode of compare defined in datasheet) and <code>OCR2A</code> is a register used to store the compare value that defines duty cycle. Imagine a counter that every time it receives a tick from a signal clock it compares the value of the counter with the value stored in <code>OCR2A</code> and it sets the pin high or low if that value as been passed or not (more or less like this, depending on the mode stored on <code>TCCR2A</code>).</p>
<p>But in fact I've not done some black magic. I just looked into the code of <code>analogWrite()</code> and that is the way they use to set a value of PWM in pin 11:</p>
<pre class="lang-c prettyprint-override"><code>void analogWrite(uint8_t pin, int val)
{
// We need to make sure the PWM output is enabled for those pins
// that support it, as we turn it off when digitally reading or
// writing with them. Also, make sure the pin is in output mode
// for consistenty with Wiring, which doesn't require a pinMode
// call for the analog output pins.
pinMode(pin, OUTPUT);
if (val == 0)
{
digitalWrite(pin, LOW);
}
else if (val == 255)
{
digitalWrite(pin, HIGH);
}
else
{
switch(digitalPinToTimer(pin))
{
...
#if defined(TCCR2A) && defined(COM2A1)
case TIMER2A:
// connect pwm to pin on timer 2, channel A
sbi(TCCR2A, COM2A1);
OCR2A = val; // set pwm duty
break;
#endif
...
}
</code></pre>
<p>So basically I just used that info to set the register to zero, as suggested from the arduino.cc forum link that you have. </p>
<p>If you want to know more about PWM in Arduino, <a href="http://www.righto.com/2009/07/secrets-of-arduino-pwm.html" rel="nofollow">this site</a> has a lot of info and explains a lot of the modes of registers also.</p>
|
17947
|
|arduino-pro-mini|
|
Newbie - What is the Difference Between Power Supply's GND and Arduino's GND?
|
2015-11-20T05:43:26.663
|
<p>I am new to electronics and Arduino.</p>
<p>What is the difference between power supply ground and Arduino's ground. If I connect my LED cathode to power ground, it doesn't work. But if I connect it to Arduino ground, it works. Aren't all ground the same? </p>
<p>Please see picture below.</p>
<p><a href="https://i.stack.imgur.com/AhDtD.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/AhDtD.png" alt="enter image description here"></a></p>
|
<p>I agree with the other answers. On rare occasions, TO-xxx packages have bizarre pinouts, but the 78xx series does, in fact, have ground on the middle terminal. This is surely a split power supply in your breadboard power busses, or else a bad breadboard. Many breadboards have splits in the power rails halfway down. I've also seen some with splits more often than that, perhaps as much as disconnects every 5 (or 5 pairs of) contacts. I have a breadboard, for example, which allows for 6 different voltages, all in a single line, from various connections to a battery pack. I'd recommend buzzing the breadboard before starting to use it. </p>
<p>I've also had breadboards whose contacts fail after using larger AWG wires in particular holes (or forcing odd connections, such as machined contacts on IC's or sockets, or larger stamped rectangular pins on a TO package such as this) into breadboard holes. The last thing you want to worry about when building a prototype of a new design is whether or not the wiring under the breadboard works.</p>
<p>Many multimeters have a continuity test capability for diagnosing problems such as these, BUT make sure no power is connected (or you could damage the meter on this setting).</p>
|
17949
|
|arduino-uno|time|rtc|
|
Library to correct time for DST
|
2015-11-20T07:19:00.197
|
<p>I am using a Uno as a data logger with a DS1307 RTC and the following libraries Time.h DS1307RTC.h</p>
<p>The DS1307 does not have any support for DST and neither library includes Time Zone.</p>
<p>Are there any libraries which adjust for DST?</p>
<hr>
<p>I used the <code>Timezone</code> module to correct my times for DST.
It took a little time to sort it out, so I though I would post the steps I followed.</p>
<p>Customise <code>WriteRules</code> for my Timezone.
I copied rule from <code>WorldClock</code>.
NOTE also need to modify Timezone in setup(void)
Run <code>WriteRules.pde</code> to write rules to EEPROM address 100</p>
<p>Run <code>TimeRTCSet.pde</code> to set RTC time to UTC.
Start Serial Monitor.
In Terminal send time to Arduino</p>
<pre><code>date -u +T%s > /dev/tty.usbmodemFA131
</code></pre>
<p>Run <code>HardwareRTC.pde</code> to demonstrate time display in UTC & local</p>
<p>I modified my sketch by including the following code:-</p>
<pre><code>#include <Timezone.h> //https://github.com/JChristensen/Timezone
⋯
Timezone myTZ(100); //assumes rules stored at EEPROM address 100
TimeChangeRule *tcr; //pointer to the time change rule, use to get TZ abbrev
time_t utc, local;
⋯
utc = now();
local = myTZ.toLocal(utc, &tcr);
</code></pre>
|
<p>You could use the <a href="https://github.com/JChristensen/Timezone" rel="nofollow">Timezone library</a>.</p>
|
17964
|
|programming|arduino-mega|memory-usage|performance|
|
OOP vs Inline with Arduino
|
2015-11-20T19:32:38.347
|
<p>I have been programming for quite a while now but I am new to Arduino and AVR Programming. The main question I have about programming these Micro-controllers is are there major differences in designing code in Object Orientated Classes vs the more traditional inline programming I have seen in many examples? </p>
<p>In other words in the world of Arduino/AVR Controllers are there any savings with Memory and Performance utilizing classes or visa versa?</p>
<p>Say for example we have a Class:</p>
<pre><code>class SomeClass(){
private:
int x;
int y;
public:
void foo();
void bar();
}
SomeClass thisClass;
thisClass.foo();
thisClass.bar();
</code></pre>
<p>Would there be any performance or memory gains designing the program in a more inline fashion like:</p>
<pre><code>int x;
int y;
void foo(){ /*** Do something ***/};
void bar(){ /*** Do more stuff ***/};
</code></pre>
<p>I tried doing some searches on Stack Exchange and Google but couldn't find quite the answer I am looking for the closest thing I was able to find was <a href="https://arduino.stackexchange.com/questions/6690/what-are-the-benfits-of-global-variables-over-static-class-members">this Stack Exchange Question.</a></p>
<p>The reason I am asking about this is I have a project that needs to be as light as possible and I am not clear how I should be designing my program in this environment.</p>
<hr>
<p><strong>Edit</strong></p>
<p>Thank you for the answers, this has shed light on things. There is one thing that I am not quite clear about. </p>
<p>Say you have a class that you are designing that utilizes the u8glib as follows:</p>
<pre><code>class UserInterface{
private:
U8GLIB_ST7920_128X64 Display;
public:
UserInterface();
}
</code></pre>
<p>How would you get around using "Dynamic Memory" like:</p>
<pre><code>UserInterface::UserInterface(){
UserInterface::Display = U8GLIB_ST7920_128X64(LCD_E_PIN, LCD_RW_PIN, LCD_RS_PIN, U8G_PIN_NONE);
}
</code></pre>
|
<blockquote>
<p>The main question I have about programming these Micro-controllers is
are there major differences in designing code in Object Orientated
Classes vs the more traditional inline programming I have seen in many
examples?</p>
<p>...</p>
<p>In other words in the world of Arduino/AVR Controllers are there any
savings with Memory and Performance utilizing classes or visa versa?</p>
</blockquote>
<p>Yes, there is a great difference between using C or C++ for small scale embedded systems such as Arduino/AVR. C++ allows more information to be provide for compiler optimizations.</p>
<p>If you are implementing an OOP framework, platform or runtime C++ and classes can also help with software architecture and reuse. In <a href="https://github.com/mikaelpatel/Cosa" rel="nofollow noreferrer">Cosa</a> a number of OOP design patterns are used to achieve interfaces for both application programmers and device driver programmers. The most common is <a href="https://en.wikipedia.org/wiki/Delegation_pattern" rel="nofollow noreferrer">delegation</a>.</p>
<p>Using abstract classes, virtual member functions, inlining, and templates can help achieve lower foot-print and higher performance than traditional implementations. As an example the Cosa Pin classes are X5-X10 faster than the Arduino core and at the same time smaller in foot-print. Please see the <a href="https://github.com/mikaelpatel/Cosa/tree/master/examples/Benchmarks" rel="nofollow noreferrer">benchmarks</a>.</p>
<p>One thing to "unlearn" from traditional C++ programming is the usage of new/delete (malloc/free). With SRAM size of only a few Kbyte using a heap is very much a risk. The answer is static classes and stack based data.</p>
<p>There is much more to be said about OOP framework architecture but I hope this helps answer your initial questions.</p>
<p>Cheers!</p>
|
17970
|
|arduino-uno|power|voltage-level|
|
5v to 4.3v Regulator - For SIM800 module
|
2015-11-20T23:00:43.730
|
<p>I want to build a simple voltage regulator 3.8-4.2V with atleast 2A Peak Current Capability for my GSM Shield (It doesn't have regulated power supply), I don't want variation or it may burn the board.</p>
<p>Using voltage divider won't help here as there can be variations.
Somewhere i read LDO are for for this task but i am able to get only 3.3v regulator with 800mA supply.</p>
<p>Can i use 3.3v to power the same ?</p>
|
<blockquote>
<p>I planned to use 3.7v LIPO battery</p>
</blockquote>
<p>That's what your SIM800 module is <em>intended</em> to be <em>directly</em> powered by, <em>without</em> any intervening boost or buck converter.</p>
<p>Behind all the misdirection of a title that doesn't describe what you are actually trying to do, your question is an exercise in going around in a circle right back to where you started. Don't try to convert energy from the lithium cell to some other voltage and then from there to the allowed input range of the SIM800 (which is very intentionally that of a single lithium cell), rather use the parts as they were intended to be used.</p>
<blockquote>
<p>i guess it has current 800mA..</p>
</blockquote>
<p>No, it has a capacity of 800 milliamp hours, not 800 milliamps.</p>
<p>A phone or RC model type lithium cell you would find today would have a "C" rating of 10 or better, but even if we assumed one of only 5, that would predict that your cell should be expected to be able to support pulse loads of 5 times the one-hour draw rate, which would be .8 * 5 = 4 amps.</p>
|
17990
|
|arduino-uno|ethernet|
|
Help putting an Arduino project on the Internet
|
2015-11-21T13:58:35.827
|
<p>I'm working on quite a big project and I need few advices. Basically, Arduino will be receiving data (Strings) and will work with it. No problems with that, but I don't know what to do with receiving and sending data. Customers (all over the country, so the program will not run on LAN) will send the data, but the question is, via what? Application, that will make a TCP connection to Arduino, send UDP packet or maybe a website? Customers need to have access to data (it needs to be refreshed when arduino deletes it too). What would be the most efficient, easy to use and reliable system?</p>
<p>Next thing I want to know is how to make a connection. Open a port on router and connect arduino to that router? I currently have a python script that actually sends an UDP packet to local IP and it works great, but it is limited to LAN. Will it work if I just change the IP (to external) and send it to the port?</p>
<p>And the last thing (for now). I know how to programm in python and java. Which one is better for connections and GUIs? </p>
<p>Thank you for your help, and if you need any more info about the project, I will be happy to edit this post. </p>
|
<p>If I'm understanding you correctly, you have your application running on a LAN and now want to figure out how to make it accessible over the Internet (WAN). If you're there the next step is relatively straight forward. All you need is an IP address that is visible on the Internet.</p>
<p>You don't say what your connection to the Internet is, so let's look at both of the likely (IPv4) possibilities:</p>
<ul>
<li><p>You have a block of publicly visible addresses (something other than an IP address starting with 10, 172.16, or 192.168 that are allocated by RFC 1918), or</p></li>
<li><p>You are behind a single IP address using NAT (network address translation) to provide the internal machines with access to the Internet. The internal machines (and devices) will all have an RFC 1918 address and will not be accessible from the Internet – except by traffic responding to requests made by those machines which are routed to them using NAT. For many users this is the more likely case.</p></li>
</ul>
<p>In the first case it is simply a matter of connecting the Arduino to a network segment that is connected to the Internet and assigning an IP address (or configuring DHCP). Also, make sure that the UDP port you are using is not assigned to another service.</p>
<p>In the second case you will also need to connect the Arduino to a network segment with access to the Internet, but because of NAT users outside will not be able to get to the Arduino (yet). To solve that problem you will need to map a port and your external address (the address of your router) to a port and the internal address of your Arduino. For example:</p>
<ul>
<li><p>Assume your service runs on port 3142 and your IP address on the Internet is 8.9.10.11 and the Arduino is at 192.168.0.42 on your internal network.</p></li>
<li><p>Then you would configure the port forwarding settings on your router to direct UDP traffic bound for port 3142 to the internal IP address of 192.168.0.42. Some routers will only allow you to forward to the same port, others will also allow you to use a different internal port as well.</p></li>
<li><p>You may also need to open up a "hole" in your firewall to allow traffic to the port where your service runs. The truly cautious will connect the Arduino to a network segment in the DMZ and there will be another firewall protecting your internal computers and devices.</p></li>
</ul>
<p>Once you have this set up anybody on the outside will be able to use the service on the Arduino – if they know the IP address and the port number. Typically you would run the service at a well known host name and use DNS to translate the host name to an IP address. From your question I can't tell how you want to advertise the service, that would be another good question…</p>
|
17993
|
|arduino-due|adc|
|
Speed of built in DAC/ADC in Arduino Due
|
2015-11-21T17:12:40.010
|
<p>Can someone tell me how fast the built in DAC (and ADC) in an Arduino Due can be written or read? I currently don't have the equipment to measure but need the information to plan my next steps. </p>
<p>I try to move galvanometer mirrors and want to make the voltage/position updates as small as possible. How fast are the internal DACs compared to an SPI connection (where I have to write 2 Byte). </p>
|
<p>See sections 43, Analog-to-Digital Converter (ADC), and 44, Digital-to-Analog Converter Controller (DACC), in the Atmel-11057-32-bit-Cortex-M3-Microcontroller-SAM3X-SAM3A_Datasheet.pdf specsheet.</p>
<p>In particular, subsection 43.2, Embedded Characteristics, says: “1 MHz Conversion Rate”. Some time diagrams appear quite a few pages later that suggest 10-bit conversions can be done more rapidly than 12-bit.</p>
<p>For the DAC (or DACC, per the specsheet), section 44.6, Functional Description, says:</p>
<blockquote>
<p>The DACC uses the master clock (MCK) divided by two to perform conversions. This clock is named DACC Clock.
Once a conversion starts the DACC takes 25 clock periods to provide the analog result on the selected analog
output.</p>
</blockquote>
<p>AIUI, the Due's master clock frequency is 84 MHz, so DACC Clock frequency is 42 MHz, whence 25 cycles take 575 ns, which is an update frequency of about 1.74 MHz.</p>
<p>For more details about the ADC, see eg <a href="http://www.djerickson.com/arduino/" rel="nofollow">
Analog performance, particularly of Due's 12 bit ADC</a> at djerickson.com.</p>
|
17994
|
|arduino-ide|eclipse|
|
One workspace, two IDEs - Possible?
|
2015-11-21T17:22:39.320
|
<p>How can I create a workspace & projects so that either the Arduino IDE or the <a href="http://www.baeyens.it/eclipse/" rel="nofollow">EclipseArduino IDE</a> may be used to develop the project, interchangeably?</p>
<p>I have both IDEs installed and working but in separate workspaces. </p>
<p>I need:</p>
<ul>
<li>One workspace that either IDE can understand and work in;</li>
<li>Either to IDE build with the physically same set of library sources;</li>
<li>Whichever IDE I open to see my sources as I last left them, regardless of which IDE I last used.</li>
</ul>
<p>I want:</p>
<ul>
<li>The source files to have conventional names - .C or .C++, not .pde or .ino;</li>
<li>Either IDE to build with the physically same set of library object modules;</li>
</ul>
<p>My use-case is that I work in/with Eclipse, and I teach Arduino skills to people starting out with the Arduino IDE. I'd like to be able to prepare class work at home with Eclipse but open and project it in class with the Arduino IDE. It would be nice if I could demonstrate the two IDEs using the same code. Clearly, I could hack up a demonstration, but I'd rather do it honestly and without sync issues like having to apply twice any changes we made in class.</p>
<p><br>Update 20 Apr '16:
At @Jantje's suggestion (in the comments below his answer), I created a github issue, "<em>Importing an ArduinoIDE project with the New Sketch Wizard and using same sketch-name, failed.</em>" The new sketch would over-write the .ino file with a new, empty sketch.</p>
<p>That issue got fixed in the April 14, 2016 nightly and now works as his answer to this question says it does. </p>
|
<p>Your requirements for not having <code>.ino</code> files and wanting to be able to work with the Arduino IDE are conflicting. Assume we drop that requirement it is very much possible to do what you want.</p>
<p>The Arduino Eclipse plugin has been supporting <code>.ino</code> files for a long time now. You can simply compile Arduino IDE-made sketches. You do not have to make links and so make the folder where your Arduino IDE makes its sketches the workspace in Eclipse.</p>
<p>In Eclipse, for each sketch you want to edit, start the new sketch wizard and use a project name that is the same as the sketch name in the Arduino IDE. </p>
<p>Now you can work in the Arduino Eclipse plugin and the Arduino IDE on the same files.</p>
<p><strong>Important:</strong> In Windows, if you use a version of the plugin from before March 3, 2016, you need to delete the <code>.ino.cpp</code> file before starting the Arduino IDE. In Linux, the Arduino IDE ignores this file, but in 1.6.7 on Windows (just tested it) the file gets picked up by the Arduino IDE. You need to restart the Arduino IDE to tell it the file is gone.</p>
<p>From March 3, 2016 onwards, the code in the <code>.ino.cpp</code> file is inside a <code>#ifdef</code> that is not defined in Arduino IDE.</p>
|
17998
|
|programming|arduino-mega|lcd|eclipse|
|
Arduino using LCD
|
2015-11-21T20:12:41.720
|
<p>I am building a project that is using A12864ZW 128X64 LCD, the question I have is should there be anything in the circuit to prevent damage to the Arduino Mega or the LCD? I am using this <a href="http://overskill.alexshu.com/128x64-12864-lcd-w-arduino-serial/" rel="nofollow">example here</a> for a start.</p>
<p>I think I damaged one LCD with the current circuit because everything was working perfect then all of a sudden it was like the LCD Contrast was set all the way up, displaying only a dark screen but I couldn't adjust it with the U8Glib or with the V0. During programming I would disconnect the ground from the Arduino to the Breadboard, when I would do this the LCD would still flicker as it was being programmed. This is why I am wondering if I am missing something.</p>
<p>I read somewhere that putting a MOSFET on the Ground of the LCD that is connected to the Reset pin helps. Another problem that I am having is I am using Eclipse with the Arduino C++ add in and sometimes I can program easily, everything goes as expected but then it will fail to upload until I unplug and reset the board sometimes several times.</p>
<p>Because the program is using pins 11-13 it can create problems because these are the same pins used for programming if I remember correctly. I tried changing the pins used but didn't seem to help anything.</p>
|
<p>Disconnecting ground while all the other pins are connected and the Arduino is powered up is a <em>very</em> bad idea. Either manually, or using a MOSFET.</p>
<p>Simply because the power you are feeding in to the screen wants to try and find a way to ground through some means or other - and if the ground is disconnected then that means muscling its way through the IO pins into the Arduino and through to ground that way. The result is that you damage the LCD screen's fragile circuitry.</p>
<p>If you want to disconnect the ground pin at any time, you must ensure that either the power is turned off, or the power connections to the LCD are disconnected first.</p>
<p>If you want to have the Arduino's RESET toggle the power to the LCD to force a hard reset then you need to use a P-channel MOSFET in the power connection instead, so the ground connection is always connected.</p>
|
18005
|
|arduino-uno|usb|android|
|
Controlling DC motor from Android device
|
2015-11-22T14:45:08.220
|
<p>Ref: <a href="https://robotics.stackexchange.com/q/8526/11146">https://robotics.stackexchange.com/q/8526/11146</a></p>
<p>I want to build a simple android controlled robot</p>
<p>I will connect <code>android phone<usb>arduino<wire>motor controller<wire>dc motor</code></p>
<p>I wonder why I have to write two programs (android java & arduino c++)?</p>
<p>How can I directly control the DC motor from android java program without writing arduino code?</p>
|
<p>The short answer is "you can't." For the Arduino to do anything useful it needs to have instructions telling it what to do. In your example the Arduino's job is to do something that the Android can't – turn on and off the DC motor. You could even use a wifi or Bluetooth connection from the Android to the Arduino to make it possible to avoid the hassle of the USB cable.</p>
<p>Your project requires a number of small hunks of code on the Arduino to:</p>
<ul>
<li>Listen for commands from the Android.</li>
<li>Validate the commands received.</li>
<li>Turn on or off the motor.</li>
</ul>
<p>Roughly speaking your loop() function might look something like this:</p>
<pre><code>void loop() {
// look for a command
// validate the command
if (valid && turn_motor_on) {
motor_on();
} else {
motor_off();
}
}
</code></pre>
<p>Fortunately the Arduino code can be very simple and there is a lot of example code to help you get started.</p>
|
18007
|
|programming|c++|string|
|
Simple URL decoding
|
2015-11-22T16:16:19.517
|
<p>How can I do a readable, small, smart and good URL decoder in Arduino?</p>
<p>Now I'm using this code:</p>
<pre><code>String GetRidOfurlCharacters(String urlChars)
{
urlChars.replace("%0D%0A", String('\n'));
urlChars.replace("+", " ");
urlChars.replace("%20", " ");
urlChars.replace("%21", "!");
urlChars.replace("%22", String(char('\"')));
urlChars.replace("%23", "#");
urlChars.replace("%24", "$");
urlChars.replace("%25", "%");
urlChars.replace("%26", "&");
urlChars.replace("%27", String(char(39)));
urlChars.replace("%28", "(");
urlChars.replace("%29", ")");
urlChars.replace("%2A", "*");
urlChars.replace("%2B", "+");
urlChars.replace("%2C", ",");
urlChars.replace("%2D", "-");
urlChars.replace("%2E", ".");
urlChars.replace("%2F", "/");
urlChars.replace("%30", "0");
urlChars.replace("%31", "1");
urlChars.replace("%32", "2");
urlChars.replace("%33", "3");
urlChars.replace("%34", "4");
urlChars.replace("%35", "5");
urlChars.replace("%36", "6");
urlChars.replace("%37", "7");
urlChars.replace("%38", "8");
urlChars.replace("%39", "9");
urlChars.replace("%3A", ":");
urlChars.replace("%3B", ";");
urlChars.replace("%3C", "<");
urlChars.replace("%3D", "=");
urlChars.replace("%3E", ">");
urlChars.replace("%3F", "?");
urlChars.replace("%40", "@");
urlChars.replace("%41", "A");
urlChars.replace("%42", "B");
urlChars.replace("%43", "C");
urlChars.replace("%44", "D");
urlChars.replace("%45", "E");
urlChars.replace("%46", "F");
urlChars.replace("%47", "G");
urlChars.replace("%48", "H");
urlChars.replace("%49", "I");
urlChars.replace("%4A", "J");
urlChars.replace("%4B", "K");
urlChars.replace("%4C", "L");
urlChars.replace("%4D", "M");
urlChars.replace("%4E", "N");
urlChars.replace("%4F", "O");
urlChars.replace("%50", "P");
urlChars.replace("%51", "Q");
urlChars.replace("%52", "R");
urlChars.replace("%53", "S");
urlChars.replace("%54", "T");
urlChars.replace("%55", "U");
urlChars.replace("%56", "V");
urlChars.replace("%57", "W");
urlChars.replace("%58", "X");
urlChars.replace("%59", "Y");
urlChars.replace("%5A", "Z");
urlChars.replace("%5B", "[");
urlChars.replace("%5C", String(char(65)));
urlChars.replace("%5D", "]");
urlChars.replace("%5E", "^");
urlChars.replace("%5F", "_");
urlChars.replace("%60", "`");
urlChars.replace("%61", "a");
urlChars.replace("%62", "b");
urlChars.replace("%63", "c");
urlChars.replace("%64", "d");
urlChars.replace("%65", "e");
urlChars.replace("%66", "f");
urlChars.replace("%67", "g");
urlChars.replace("%68", "h");
urlChars.replace("%69", "i");
urlChars.replace("%6A", "j");
urlChars.replace("%6B", "k");
urlChars.replace("%6C", "l");
urlChars.replace("%6D", "m");
urlChars.replace("%6E", "n");
urlChars.replace("%6F", "o");
urlChars.replace("%70", "p");
urlChars.replace("%71", "q");
urlChars.replace("%72", "r");
urlChars.replace("%73", "s");
urlChars.replace("%74", "t");
urlChars.replace("%75", "u");
urlChars.replace("%76", "v");
urlChars.replace("%77", "w");
urlChars.replace("%78", "x");
urlChars.replace("%79", "y");
urlChars.replace("%7A", "z");
urlChars.replace("%7B", String(char(123)));
urlChars.replace("%7C", "|");
urlChars.replace("%7D", String(char(125)));
urlChars.replace("%7E", "~");
urlChars.replace("%7F", "Â");
urlChars.replace("%80", "`");
urlChars.replace("%81", "Â");
urlChars.replace("%82", "â");
urlChars.replace("%83", "Æ");
urlChars.replace("%84", "â");
urlChars.replace("%85", "â¦");
urlChars.replace("%86", "â");
urlChars.replace("%87", "â¡");
urlChars.replace("%88", "Ë");
urlChars.replace("%89", "â°");
urlChars.replace("%8A", "Å");
urlChars.replace("%8B", "â¹");
urlChars.replace("%8C", "Å");
urlChars.replace("%8D", "Â");
urlChars.replace("%8E", "Ž");
urlChars.replace("%8F", "Â");
urlChars.replace("%90", "Â");
urlChars.replace("%91", "â");
urlChars.replace("%92", "â");
urlChars.replace("%93", "â");
urlChars.replace("%94", "â");
urlChars.replace("%95", "â¢");
urlChars.replace("%96", "â");
urlChars.replace("%97", "â");
urlChars.replace("%98", "Ë");
urlChars.replace("%99", "â¢");
urlChars.replace("%9A", "Å¡");
urlChars.replace("%9B", "âº");
urlChars.replace("%9C", "Å");
urlChars.replace("%9D", "Â");
urlChars.replace("%9E", "ž");
urlChars.replace("%9F", "Ÿ");
urlChars.replace("%A0", "Â");
urlChars.replace("%A1", "¡");
urlChars.replace("%A2", "¢");
urlChars.replace("%A3", "£");
urlChars.replace("%A4", "¤");
urlChars.replace("%A5", "Â¥");
urlChars.replace("%A6", "¦");
urlChars.replace("%A7", "§");
urlChars.replace("%A8", "¨");
urlChars.replace("%A9", "©");
urlChars.replace("%AA", "ª");
urlChars.replace("%AB", "«");
urlChars.replace("%AC", "¬");
urlChars.replace("%AE", "®");
urlChars.replace("%AF", "¯");
urlChars.replace("%B0", "°");
urlChars.replace("%B1", "±");
urlChars.replace("%B2", "²");
urlChars.replace("%B3", "³");
urlChars.replace("%B4", "´");
urlChars.replace("%B5", "µ");
urlChars.replace("%B6", "¶");
urlChars.replace("%B7", "·");
urlChars.replace("%B8", "¸");
urlChars.replace("%B9", "¹");
urlChars.replace("%BA", "º");
urlChars.replace("%BB", "»");
urlChars.replace("%BC", "¼");
urlChars.replace("%BD", "½");
urlChars.replace("%BE", "¾");
urlChars.replace("%BF", "¿");
urlChars.replace("%C0", "Ã");
urlChars.replace("%C1", "Ã");
urlChars.replace("%C2", "Ã");
urlChars.replace("%C3", "Ã");
urlChars.replace("%C4", "Ã");
urlChars.replace("%C5", "Ã");
urlChars.replace("%C6", "Ã");
urlChars.replace("%C7", "Ã");
urlChars.replace("%C8", "Ã");
urlChars.replace("%C9", "Ã");
urlChars.replace("%CA", "Ã");
urlChars.replace("%CB", "Ã");
urlChars.replace("%CC", "Ã");
urlChars.replace("%CD", "Ã");
urlChars.replace("%CE", "Ã");
urlChars.replace("%CF", "Ã");
urlChars.replace("%D0", "Ã");
urlChars.replace("%D1", "Ã");
urlChars.replace("%D2", "Ã");
urlChars.replace("%D3", "Ã");
urlChars.replace("%D4", "Ã");
urlChars.replace("%D5", "Ã");
urlChars.replace("%D6", "Ã");
urlChars.replace("%D7", "Ã");
urlChars.replace("%D8", "Ã");
urlChars.replace("%D9", "Ã");
urlChars.replace("%DA", "Ã");
urlChars.replace("%DB", "Ã");
urlChars.replace("%DC", "Ã");
urlChars.replace("%DD", "Ã");
urlChars.replace("%DE", "Ã");
urlChars.replace("%DF", "Ã");
urlChars.replace("%E0", "Ã");
urlChars.replace("%E1", "á");
urlChars.replace("%E2", "â");
urlChars.replace("%E3", "ã");
urlChars.replace("%E4", "ä");
urlChars.replace("%E5", "Ã¥");
urlChars.replace("%E6", "æ");
urlChars.replace("%E7", "ç");
urlChars.replace("%E8", "è");
urlChars.replace("%E9", "é");
urlChars.replace("%EA", "ê");
urlChars.replace("%EB", "ë");
urlChars.replace("%EC", "ì");
urlChars.replace("%ED", "Ã");
urlChars.replace("%EE", "î");
urlChars.replace("%EF", "ï");
urlChars.replace("%F0", "ð");
urlChars.replace("%F1", "ñ");
urlChars.replace("%F2", "ò");
urlChars.replace("%F3", "ó");
urlChars.replace("%F4", "ô");
urlChars.replace("%F5", "õ");
urlChars.replace("%F6", "ö");
urlChars.replace("%F7", "÷");
urlChars.replace("%F8", "ø");
urlChars.replace("%F9", "ù");
urlChars.replace("%FA", "ú");
urlChars.replace("%FB", "û");
urlChars.replace("%FC", "ü");
urlChars.replace("%FD", "ý");
urlChars.replace("%FE", "þ");
urlChars.replace("%FF", "ÿ");
return urlChars;
}
</code></pre>
<p>However I want to make a loop and only replace a url escaping if it exists, not trying to replace all the (possible) occurrences.</p>
|
<p>I wrote a <a href="http://www.gammon.com.au/forum/?id=12942" rel="nofollow">Tiny web server</a> for the Arduino which has a similar thing in it. You might find it useful for your project. Inside there is a function that decodes the URL codes on-the-fly (ie. in a state machine). The code is a bit different to Majenko's because he assumes that you have the string in memory. In my case I am decoding a byte at a time (so you don't have to hold a long string in memory before you decode it).</p>
<p>The snippet that does the decoding is this:</p>
<pre class="lang-C++ prettyprint-override"><code> // percent-encoding: possible states
enum EncodePhaseType {
ENCODE_NONE,
ENCODE_GOT_PERCENT,
ENCODE_GOT_FIRST_CHAR,
};
// percent-encoding: current state
EncodePhaseType encodePhase;
byte encodeByte; // encoded byte being assembled (first nybble)
</code></pre>
<p>...</p>
<pre class="lang-C++ prettyprint-override"><code>// ---------------------------------------------------------------------------
// add a character to the value buffer - percent-encoded (if wanted)
// ---------------------------------------------------------------------------
void HTTPserver::addToValueBuffer (byte inByte, const bool percentEncoded)
{
if (valueBufferPos >= MAX_VALUE_LENGTH)
{
flags |= FLAG_VALUE_BUFFER_OVERFLOW;
return;
} // end of overflow
// look for stuff like "foo+bar" (turn the "+" into a space)
// and also "foo%21bar" (turn %21 into one character)
if (percentEncoded)
{
switch (encodePhase)
{
// if in "normal" mode, turn a "+" into a space, and look for "%"
case ENCODE_NONE:
if (inByte == '+')
inByte = ' ';
else if (inByte == '%')
{
encodePhase = ENCODE_GOT_PERCENT;
return; // no addition to buffer yet
}
break;
// we had the "%" last time, this should be the first hex digit
case ENCODE_GOT_PERCENT:
if (isxdigit (inByte))
{
byte c = toupper (inByte) - '0';
if (c > 9)
c -= 7; // Fix A-F
encodeByte = c << 4;
encodePhase = ENCODE_GOT_FIRST_CHAR;
return; // no addition to buffer yet
}
// not a hex digit, give up
encodePhase = ENCODE_NONE;
flags |= FLAG_ENCODING_ERROR;
break;
// this should be the second hex digit
case ENCODE_GOT_FIRST_CHAR:
if (isxdigit (inByte))
{
byte c = toupper (inByte) - '0';
if (c > 9)
c -= 7; // Fix A-F
inByte = encodeByte | c;
}
else
flags |= FLAG_ENCODING_ERROR;
// done with encoding it, or not a hex digit
encodePhase = ENCODE_NONE;
} // end of switch on encodePhase
} // end of percent-encoded
// add to value buffer, encoding has been dealt with
valueBuffer [valueBufferPos++] = inByte;
valueBuffer [valueBufferPos] = 0; // trailing null-terminator
} // end of HTTPserver::addToValueBuffer
</code></pre>
|
18015
|
|arduino-uno|i2c|lcd|compile|
|
LCD 16*02 I2C shield only shows first character printed
|
2015-11-22T19:32:18.460
|
<p>I have an I2C LCD screen provided with a Sunfounder kit and certainly built by DFRobot or such a constructor (there is nothing written on the LCD), and an Arduino Uno R3 copy.</p>
<p>My issue is when I use <code>lcd.print()</code> to write a string on the LCD, only the <strong>first character</strong> of the string is printed. I can only print on other positions by using setCursor but only one character at a time.</p>
<p>I tried to change libraries (<a href="https://github.com/fdebrabander/Arduino-LiquidCrystal-I2C-library" rel="nofollow" title="github">https://github.com/fdebrabander/Arduino-LiquidCrystal-I2C-library</a>, the one supplied with the LCD...), It always behaves the same!</p>
<p>For example, here's a very simplistic program which exhibits this behavior:</p>
<pre><code>#include <LiquidCrystal_I2C.h>
LiquidCrystal_I2C lcd(0x27, 16, 2);
// set the LCD address to 0x27 for a 16 chars and 2 line display
void setup() {
lcd.init();
lcd.backlight();
}
void loop() {
lcd.print("write");
delay(1000);
lcd.setCursor(10, 0);
lcd.print("p10");
lcd.setCursor(0, 1);
lcd.print("0, 1 write");
if((millis() / 1000) % 5 == 0) {
lcd.clear();
delay(1000);
}
}
</code></pre>
<p>I end up with something like:</p>
<pre><code>w p
0w
</code></pre>
<p>On the screen (before the <code>clear()</code> occurs of course).</p>
<p>Instead of something like:</p>
<pre><code>write p10
0, 1 writewrite
</code></pre>
<p>The lcd itself was ok some time ago. The only thing I could think is I recently updated to Arduino 1.6.6. Can it be a bug in the compiler?</p>
<p><a href="http://www.dfrobot.com/index.php?route=product/product&path=156_53&product_id=135" rel="nofollow" title="The hello world from dfrobot">The hello world from DFRobot</a> also doesn't work properly (first char only, again) (please note to make it display something with my LCD I have to change the address from 0x20 to 27).</p>
|
<p>I had the same problem. My LCD only showed one character. I downloaded and tryed docens of LCD libraries and ended up with a bunch of libraries installed in my IDE. After days trying to solve the problem I decided to clear my IDE deleting the libraries directory (mind that the IDE could take them from documents/arduino/library folder). After that I tested one by one the LCD libraries. I case it did not work I deleted it. The one posted above <a href="https://github.com/marcoschwartz/LiquidCrystal_I2C" rel="nofollow noreferrer">https://github.com/marcoschwartz/LiquidCrystal_I2C</a> worked!!.I don't really know where was the problem exactly, maybe a conflict among the libraries intalled.</p>
|
18016
|
|voltage-level|esp8266|
|
When it says the Uno has logic level at 5 V is that also true of a bareduino/breadboard Arduino?
|
2015-11-22T19:44:05.080
|
<p>I want to hook up ESP8266, which has a 3.3v logic level to my bare-bones Arduino (basically a minimal interface for the ATmega382P IC).</p>
<p>I can power my circuit at 3.3 V without a 5 V regulator so will the voltage of the logic level also be 3.3 V?</p>
<p>I don't think there is a tiny boost converter in the IC... but I'm uncertain. </p>
|
<p>The logic level is the same as the voltage you supply the chip.</p>
<p>You can think of the IO pins as tiny switches that either connect the output pin to the supply voltage or to ground (when in output mode) or compare the incoming voltage to an input pin to a percentage of the supply voltage (typically <0.3×Vcc for low and >0.6Vcc for high)</p>
<p>So yes, if you run the chip at 3.3V the logic level will be 3.3V logic (or more specifically < 1.1v for low and > 2.2v for high).</p>
|
18018
|
|enclosure|
|
What killed it? Arduino in resin
|
2015-11-22T19:48:35.237
|
<p>I made a simple circuit controlled by the ATMEGA IC then tried to encase it in resin. It died. What is the thing that caused it to die? I've had other circuits working fine in resin. I want to try again, what steps can I take to prevent this?</p>
<p>I've looked for obvious shorts but can find none. </p>
<p>Resin heats up when it cures, could that be the issue?</p>
<p><a href="https://i.stack.imgur.com/WaMDY.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/WaMDY.jpg" alt="enter image description here"></a></p>
|
<p>Potting of circuits can lead to various issues. It can't be told exactly what caused your device to fail until you uncover it like an archeologist.</p>
<p>Common problems are:</p>
<ul>
<li>Resin entering a spring loaded contact and canceling out contact forces</li>
<li>Resin exsuding corrosive substances ruining contacts</li>
<li>Resin expanding during curing and opening spring contacts or even breaking up solder contacts</li>
<li>Same effect after cool down of resin</li>
</ul>
<p>Later and often unexpected problems are:</p>
<ul>
<li>thin gaps around potted objects (i.e. no surface contact) literally sucking in water. </li>
<li>potting material producing water itself during curing.</li>
</ul>
<p>Many of these problems can be circumvented by applying conformal coating, as suggested by comments and apparently proven right by your experiments.
If it is not necessary refrain from using sockets and solder connections directly to the components. You won't be able to salvage them, anyway.</p>
|
18022
|
|button|relay|ir|
|
Controlling relays with IR and button
|
2015-11-22T21:33:49.090
|
<p>What I have:</p>
<ul>
<li>1 x 8 channel relay</li>
<li>1 x IR receiver</li>
<li>1x Arduino Uno</li>
<li>1x momentary switch</li>
<li>1x breadboard</li>
<li>1x 10K resister</li>
</ul>
<p>I think the wiring is all ok as for the most part things are working as they should..ish.</p>
<p>Just a few bugs I need to fix.</p>
<p>The goal was to toggle just 2 relays (at the moment) on/off with the hardwired switch and individually toggle the a relay using an IR remote control. </p>
<p>Like I said this sort of works....</p>
<p>If I press the momentary button it does indeed toggle both relays...yeah!
then as long as the 2 relays are toggled to the on position by the momentary switch I can toggle each relay using buttons on a remote. </p>
<p>However if I turn the relays off with the momentary button I can't turn them on with the remote. Also if I turn off one of the relays with the remote and then press momentary switch it alternates the toggle between the 2 relays rather than just turning the other one off.</p>
<p>I have been using various example sketches to achieve all this and just trying to stitch them together as best I can but something is telling me that the approach is all wrong and that I should maybe be looking into Boolean's perhaps? </p>
<p>Hope you can shed some light on this for me. </p>
<pre class="lang-c prettyprint-override"><code>#include <IRremote.h>
#define irPin 8
IRrecv irrecv(irPin);
decode_results results;
const int buttonPin = 2;
const int relay1 = 13;
const int relay2 = 12;
int relay1State;
int relay2State;
int buttonState;
int lastButtonState;
long lastDebounceTime = 0;
long debounceDelay = 50;
void setup() {
Serial.begin(9600);
irrecv.enableIRIn();
pinMode(buttonPin, INPUT);
pinMode(relay1, OUTPUT);
pinMode(relay2, OUTPUT);
digitalWrite(relay1, relay1State);
digitalWrite(relay2, relay2State);
}
void loop() {
if (irrecv.decode(&results)) {
switch (results.value) {
case 0xFF30CF:
Serial.println("Button 1 Pressed");
relay1State = ~relay1State;
digitalWrite(relay1, relay1State);
delay(250);
break;
case 0xFF18E7:
Serial.println("button 2 pressed");
relay2State = ~relay2State;
digitalWrite(relay2, relay2State);
delay(250);
break;
}
irrecv.resume();
}
int reading = digitalRead(buttonPin);
if (reading != lastButtonState) {
lastDebounceTime = millis();
}
if ((millis() - lastDebounceTime) > debounceDelay) {
if (reading != buttonState) {
buttonState = reading;
if (buttonState == HIGH) {
relay1State = !relay1State;
relay2State = !relay2State;
}
}
}
digitalWrite(relay1, relay1State);
digitalWrite(relay2, relay2State);
lastButtonState = reading;
}
</code></pre>
|
<p>So according to your comments this should be the code if no mistake was made</p>
<pre class="lang-c prettyprint-override"><code>#include <IRremote.h>
#define irPin 8
IRrecv irrecv(irPin);
decode_results results;
const int buttonPin = 2;
const int relay1 = 13;
const int relay2 = 12;
int relay1State = 0;
int relay2State = 0;
int masterState = 0;
int buttonState;
int lastButtonState;
long lastDebounceTime = 0;
long debounceDelay = 50;
void setup() {
Serial.begin(9600);
irrecv.enableIRIn();
pinMode(buttonPin, INPUT);
pinMode(relay1, OUTPUT);
pinMode(relay2, OUTPUT);
digitalWrite(relay1, relay1State);
digitalWrite(relay2, relay2State);
}
void loop() {
if (irrecv.decode(&results)) {
switch (results.value) {
case 0xFF30CF:
Serial.println("Button 1 Pressed");
relay1State = !relay1State;
digitalWrite(relay1, relay1State);
delay(250);
break;
case 0xFF18E7:
Serial.println("button 2 pressed");
relay2State = !relay2State;
digitalWrite(relay2, relay2State);
delay(250);
break;
}
irrecv.resume();
}
int reading = digitalRead(buttonPin);
if (reading != lastButtonState) {
lastDebounceTime = millis();
}
if ((millis() - lastDebounceTime) > debounceDelay) {
if (reading != buttonState) {
buttonState = reading;
if (buttonState == HIGH) {
masterState = !masterState;
relay1State = masterState;
relay2State = masterState;
}
}
}
digitalWrite(relay1, relay1State);
digitalWrite(relay2, relay2State);
lastButtonState = reading;
}
</code></pre>
<p>what I've done is create a masterState that only changes whenever you press the buttonPin and by pressing it will also change both relays to the value of new masterState independently of their actual state.</p>
<p>Another advice: is a bad practice to not initialize variables before use, because when you declare it is not granted that they are automatically equal to zero.</p>
|
18023
|
|arduino-uno|i2c|wire-library|
|
Modifying Arduino IMU library to rely on DSSCircuit's I2C Master Library
|
2015-11-22T22:04:47.223
|
<p>For an Arduino project I am working on, I am trying to modify the SparkFun 6 Degrees of Freedom IMU Digital Combo Board - ITG3200/ADXL345 to support DSSCircuit's I2C Master Library (<a href="https://github.com/DSSCircuits/I2C-Master-Library" rel="nofollow">https://github.com/DSSCircuits/I2C-Master-Library</a>). This is to combat the known issue of the Arduino Wire library to often get hung up while trying to run the EndTransmission function.</p>
<p>I'm new to this and do not understand how the terms 'slave address' and 'register address' and 'bytes you want to send' are different, if they are. I also do not understand how buffering works in the base IMU library. Any information on those would be appreciated, but is not the focus of my question.</p>
<p>I use the example code of the IMU unit...</p>
<pre><code>#include <FreeSixIMU.h>
#include <FIMU_ADXL345.h>
#include <FIMU_ITG3200.h>
#include <Wire.h>
#include <I2C.h>
int raw[6]; // x y z yaw pitch roll
// Set the FreeSixIMU object
FreeSixIMU sixDOF = FreeSixIMU();
void setup() {
Serial.begin(9600);
I2c.begin();
delay(100);
sixDOF.init(); //begin the IMU
delay(100);
}
void loop() {
sixDOF.getRawValues(raw);
Serial.print(raw[0]);
Serial.print(" x | ");
Serial.print(raw[1]);
Serial.print(" y | ");
Serial.print(raw[2]);
Serial.println(" z");
delay(100);
}
</code></pre>
<p>And I changed the selected IMU library functions as follows:</p>
<pre><code>// Writes val to address register on device
void ADXL345::writeTo(byte address, byte val) {
I2c.write(address, val);
// send register address
}
// Reads num bytes starting from address register on device in to _buff array
void ADXL345::readFrom(byte address, int num, byte _buff[]) {
I2c.read(address, (byte) num);
// sends address to read from
}
void ITG3200::writemem(uint8_t _addr, uint8_t _val) {
I2c.write(_addr, _val); // start transmission to device
}
void ITG3200::readmem(uint8_t _addr, uint8_t _nbytes, uint8_t __buff[]) {
I2c.read(_addr, _addr, _nbytes); // start transmission to device
}
</code></pre>
<p>And added the <code>#include <I2C.h></code> statements to the headers files where applicable.</p>
<p>When running the example code, the serial output will not change values based on how I move the accelerometer, which makes me think I used the wrong slave address to read data from, or some other issue.</p>
<p>Can someone help me modify the IMU library to include DSSCircuit's Master I2C Library?</p>
<p>Thank you Stack Exchange Community!
John</p>
<p><strong>EDIT:</strong></p>
<p>Please see PersonAGem's edit below. Using the wire library is known to have arbitrary hangups, and in this example PersonAGem lists the edits I should make to the other libraries I am using as well as gives me the code I should use in my <code>.ino</code>.</p>
<p>I ask a new question about this topic <a href="https://arduino.stackexchange.com/questions/18256/using-arduino-shield-seems-to-break-serial-print-and-uploading-new-code">here</a>.</p>
|
<p>You are missing the rest of the code in reading operations. You are just requesting the data, no actually reading it from the device:</p>
<p>the original code of adlx345::read</p>
<pre class="lang-c prettyprint-override"><code>void ADXL345::readFrom(byte address, int num, byte _buff[]) {
Wire.beginTransmission(_dev_address); // start transmission to device
Wire.write(address); // sends address to read from
Wire.endTransmission(); // end transmission
Wire.beginTransmission(_dev_address); // start transmission to device
Wire.requestFrom(_dev_address, num); // request 6 bytes from device
int i = 0;
while(Wire.available()) // device may send less than requested (abnormal)
{
_buff[i] = Wire.read(); // receive a byte
i++;
}
if(i != num){
status = ADXL345_ERROR;
error_code = ADXL345_READ_ERROR;
}
Wire.endTransmission(); // end transmission
}
</code></pre>
<p>would change to (if no mistakes made):</p>
<pre class="lang-c prettyprint-override"><code>void ADXL345::readFrom(byte address, int num, byte _buff[]) {
I2c.read(_dev_address, address, num) // request 6 bytes from device
if(I2c.available() != num){ // device may send less than requested (abnormal)
status = ADXL345_ERROR;
error_code = ADXL345_READ_ERROR;
}
int i = 0;
while(I2c.available())
{
_buff[i] = I2c.receive(); // receive a byte
i++;
}
}
</code></pre>
<p>you may need to force cast parameters between functions.</p>
<p>If for some reason you don't want the actual code and want to use another library, I'll suggest <a href="http://www.i2cdevlib.com/devices" rel="nofollow">I2Cdev site</a> with a well documented classes for adlx345 and ITG3200.</p>
<p><strong>Edit:</strong></p>
<p>This caused me no problem. That is the only 2 functions I changed:</p>
<pre class="lang-c prettyprint-override"><code>// Writes val to address register on device
void ADXL345::writeTo(byte address, byte val) {
I2c.write((uint8_t) _dev_address, (uint8_t) address, (uint8_t) val);
}
// Reads num bytes starting from address register on device in to _buff array
void ADXL345::readFrom(byte address, int num, byte _buff[]) {
I2c.read((uint8_t) _dev_address, (uint8_t) address, (uint8_t) num); // request 6 bytes from device
if(I2c.available() != num){ // device may send less than requested (abnormal)
status = ADXL345_ERROR;
error_code = ADXL345_READ_ERROR;
}
int i = 0;
while(I2c.available())
{
_buff[i] = I2c.receive(); // receive a byte
i++;
}
}
</code></pre>
<p><strong>Arduino code used:</strong></p>
<pre class="lang-c prettyprint-override"><code>#include <I2C.h>
#include "FIMU_ADXL345.h"
ADXL345 acc = ADXL345();
int x=0, y=0, z=0;
void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
I2c.begin();
delay(100);
acc.init(ADXL345_ADDR_ALT_LOW);
delay(100);
Serial.print("Is ACC OK?: ");
Serial.println(acc.status);
Serial.print("Any Error code?: ");
Serial.println(acc.error_code);
Serial.println("********Print all register current values********");
acc.printAllRegister();
Serial.println("********END register print******");
Serial.println(acc.getRate());
}
void loop() {
// put your main code here, to run repeatedly:
acc.readAccel(&x,&y,&z);
Serial.print(x);
Serial.print('\t');
Serial.print(y);
Serial.print('\t');
Serial.println(z);
delay(500);
}
</code></pre>
<p><strong>Output given:</strong></p>
<pre><code>Is ACC OK?: 1
Any Error code?: 0
********Print all register current values********
0x00: B11100101
0x1D: B00000000
0x1E: B00000000
0x1F: B00000000
0x20: B00000000
0x21: B00000000
0x22: B00000000
0x23: B00000000
0x24: B00000000
0x25: B00000000
0x26: B00000000
0x27: B00000000
0x28: B00000000
0x29: B00000000
0x2A: B00000000
0x2B: B00000000
0x2C: B00001010
0x2D: B00001000
0x2E: B00000000
0x2F: B00000000
0x30: B10000011
0x31: B00000000
0x32: B11110101
0x33: B11111111
0x34: B00000011
0x35: B00000000
0x36: B11100101
0x37: B00000000
0x38: B00000000
0x39: B00000000
********END register print******
100.00
-12 4 230
-10 2 231
-11 3 231
-12 3 228
-10 3 230
-11 2 231
-12 2 229
-11 3 229
-10 3 231
-11 3 229
-10 2 230
-12 4 230
-12 3 229
-10 2 229
-13 4 230
-11 3 230
-10 3 230
-11 2 230
-11 4 229
-11 3 230
-11 3 230
-11 3 229
-12 3 229
-10 2 229
-11 3 230
-11 3 231
-11 3 230
-15 14 227
34 104 210
138 95 191
243 18 88
323 -15 74
280 -8 -2
263 -2 37
212 10 163
16 39 233
28 114 195
29 161 170
33 124 211
5 49 244
7 22 224
-10 3 229
-11 2 230
-12 2 230
-11 3 231
-12 4 228
</code></pre>
|
18035
|
|shields|pins|
|
"Sharing" used GPIO pins
|
2015-11-23T09:37:14.127
|
<p>I have a question regarding the ARDuino uno and some shields. I currently have a shield on my Uno, which takes the pins 0 to 7. However, on top of that board there is an extension of those 8 pins. If they were always in use, I suppose that the extra ports wouldn't be on top of the board, right?</p>
<p>Here's how it looks: <a href="https://i.stack.imgur.com/QAxHa.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/QAxHa.png" alt="arduino shield"></a></p>
<p>So it seems like you're able to "share" them. Is it possible to do so in real-time or is that there so you can use the ports when you disable the shield?</p>
<p>If its possible in real-time, how would I go about doing that? I've searched a little but couldn't find anything. I suppose i'd need some kind of clock to make the switch between the shield and the other components on pins 0-7, but not sure how to do that.</p>
<p>I'm kind of an electrics newbie, so hence the question might be a little silly :)</p>
|
<p>No, you can't "share" pins between shields, except in specific circumstances (open-drain interrupts, I2C or SPI buses, etc). General GPIO pins connect to just one device at a time.</p>
<p>I can't tell from that picture, but it is highly unlikely that all 8 of the IO pins are actually in use by the shield, and the ones that aren't actually connected to anything within the shield are available for another shield placed on top to use. You'll have to look at the schematic or manual for the shield to know exactly which pins are used for what and which are available for other shields to use.</p>
<p>However, one thing to note with that shield - it doesn't appear to pass through the power header, so how a shield on top would get powered at all is a mystery to me.</p>
|
18037
|
|software|
|
Updating the ARDuino code over GPRS
|
2015-11-23T09:44:57.547
|
<p>I've been searching a little for self-updating the ARDuino, and most i've come about is updating it using a wifi / lan shield.</p>
<p>Now I have a GPRS shield that can connect it to the internet. Say that I want to remotely update the shield - how would I go about doing that?</p>
<p>I'm guessing I need some kind of bootloader - but is that extra hardware?</p>
<p>Actually the question boils down to:</p>
<ul>
<li>How can I flash the ARDuino Uno with new software, that I'll receive over a GPRS connection using a GPRS shield?</li>
</ul>
|
<p>You would either have to replace the bootloader on your chip (software) with one that knows about your GPRS shield (I don't know if there is one, so you would most likely have to write your own and that is not a trivial task), or use a second microcontroller to act as a programming interface between the GPRS shield and the main Arduino. That could be another Arduino.</p>
<p>The second option is probably the simplest to create:</p>
<ol>
<li>The GPRS is connected to Arduino A.</li>
<li>Your main software runs on Ardiuno B.</li>
<li>Both Arduinos are connected by serial</li>
<li>Normal operation Arduino A passes all serial verbatim through to Arduno B</li>
<li>Arduino A receives programming instructions and downloads the new code - maybe storing it on an SD card temporarily (not enough RAM in an Arduino) then resets Arduino B into the bootloader.</li>
<li>Arduino A then sends the serial instructions in the same way that avrdude does to program the downloaded HEX file.</li>
</ol>
<p>Arduino A is then a proxy between the GPRS and Arduino B. Arduino A does all the control of the GPRS and sends data between Arduino A and the internet and vice versa - it's up to you to decide how best to achieve that, depending on what information you have going backwards and forwards.</p>
<p>Both solutions require a certain level of programming knowledge and skill and aren't trivial, but are perfectly possible if you set your mind to it.</p>
|
18043
|
|arduino-yun|python|
|
Share data between the two processors of the Arduino Yun
|
2015-11-23T14:29:00.160
|
<p>The linux processor runs a Python script from which I would like to send an array of integers to the Yun microprocessor. How can I do that?</p>
<p>And then, how can I retrieve and then use this array in my Arduino Sketch?</p>
|
<p>The Yun makes communication between the microprocessor and the Linux side easy. On the Arduino side, use the Bridge library in your "processing script" to read (or write) Bridge values set by the python program running on the Linux side. From the linux side, the bridge looks like a web address and you set values by addressing a URL with a get or put url http request. You can also manipulate these values from another computer on the network as well if you like.</p>
<p>I have some Arduino Yun dataloggers that use the Linux side to communicate via wifi with an ftp server that serves several Yun dataloggers. The arduino script reads the sensors, creates the records, etc. You can also have the microprocessor side write files that are used by the linux side of the Yun. </p>
<p>I find the Yun's combination of Linux and the regular arduino in one package makes the overall system easier to program and to interface with the rest of the web.</p>
|
18045
|
|communication|nrf24l01+|string|variables|
|
Run code via NRF24L01+ command "dynamically"?
|
2015-11-23T15:43:17.687
|
<p>I'm trying to make a home automation setup but I'm having a bit of trouble.</p>
<p>I want to be able to send commands of varying sizes to my arduino, separated by "|" and after receiving it completely it runs code corresponding to the command.</p>
<p>Example: </p>
<p>input "RCP=10001|CMD=D|VAL=120"
would result in an array like: </p>
<pre><code>String cmd[][] = {{"RCP", "10001"}, {"CMD", "D"}, {"VAL", "120"}}
</code></pre>
<p>with the amount of 'variables' being... well, variable. </p>
<p>The code would continue checking if the RCP (recipient) ID corresponds with the ID of the current client and then run code based on the following variables.
But I don't think that's important info for the code which separated the string.</p>
<p>This string would be sent through an NRF24L01+ (That code already works)</p>
|
<p>What you are asking is very tricky at best. Your average Arduino doesn't have enough memory to start storing arrays of Strings.</p>
<p>Instead you will need to "distil" the information as it comes in and store the distilled information.</p>
<p>If the possible keys are all known beforehand then you can assign a number to each possible key - say RCP is 1, CMD is 2, VAL is 3, etc. If the values are all numeric or can be represented by a number, then convert those to the corresponding number and store those.</p>
<p>Also the Arduino is not good at working with dynamic memory allocations - again because of lack of memory. If you can decide on a reasonable maximum number of messages to store then you can pre-allocate the memory for them.</p>
<p>For instance it may be good to define a structure which is the content of a message:</p>
<pre><code>struct message {
uint8_t key;
uint16_t val;
};
</code></pre>
<p>Then make an array of that structure - one slice per possible command, say 10 of them:</p>
<pre><code>struct message messageQueue[10];
</code></pre>
<p>That would take a total of 30 bytes in memory - each entry being 3 bytes (1 for the key, two for the value). Now you can set the keys and values to the correct data as it arrives.</p>
<p>Depending on how you want to deal with the messages as they come in - add them to the end of an existing queue, or always starting the queue from empty every time a new message arrives - you might want to implement a <em>circular buffer</em>. This is basically how the Serial port on the Arduino works - in involves having two <em>pointers</em> to locations in the array - one where you are writing to, and one where you are reading from. As you write to the array the writing pointer moves along - if it reaches the end it starts from the beginning again. As you read from the array the reading pointer moves along too. If the two pointers are together then the array is empty. If the writing pointer would end up where the reading pointer is, the array is full. Take a look in the Arduino source code (HardwareSerial.cpp) to see how it's implemented.</p>
<p>As for parsing the string as it comes in - if you have it as a single String already then it's a case of looking through it for the | characters and splitting out each portion in turn, then doing the same with each portion looking for the =. Then you can interpret what is in the key/value pairs and decide what to store in the array.</p>
|
18074
|
|arduino-uno|ethernet|
|
TCP connection CPU usage, multiple signals?
|
2015-11-24T18:28:58.900
|
<p>I'm connecting a client (java program) to an arduino (server). What I want to know is, how high the CPU usage is, and what to do if there are no clients that are trying to connect to arduino? Should I make a delay?</p>
<p>My code looks like this:</p>
<pre><code>EthernetClient client = server.available();
if(client){
Serial.println("Connected");
server.write("Hello\n");
//check if client is still connected
while (client.connected()){
Serial.println("Still there");
delay(2000);
//check if client received any data
if(client.available()){
//read message from client
}
}
} else {
Serial.println("Nope");
server.write("Hello\n");
???????????? delay(2000); ??????????????
}
</code></pre>
<p>Thank you for your help.</p>
|
<p>As the Arduino typically has no demand-based clock scaling, or alternate threads of comparable priority you can schedule, there's really little point in using a delay (which is implemented as a busy-wait) rather than a tight loop - really, the primary appropriate reason would be to reduce the frequency of status output.</p>
<p>However, if you want to design a power-efficient system, you could consider sleeping the CPU between checking if there is anything worthwhile to do, or until an interrupt indicates that there is. This is not something which delay() will take care of for you, so it is a fair amount of extra work and testing to get right, but it can be very worthwhile if running from batteries.</p>
<p>If your application is not particularly intensive you can also configure the clock divider fuse and slow the chip down generally.</p>
|
18075
|
|arduino-uno|
|
sending multiple signals at the same time, with short delay
|
2015-11-24T20:51:45.897
|
<p>Is it possible to do something like this: send a HIGH signal to an output pin, after a 0.33s delay arduino sends HIGH signal to another pin, and after another 0.33s delay, arduino sends signal to third pin. There has to be 90 seconds long high signal for each pin, but with 0.33s delay between each other. </p>
<p>Sooo something like this; start of the high signal on left, stop on right side:</p>
<pre><code>pin1: 0 ...... 90.00
pin2: 0.33 ... 90.33
pin3: 0.66 ... 90.66
</code></pre>
<p>Is there a way to solve this?</p>
|
<p>Yes. Read the BlinkWithoutDelay example and triplicate it.</p>
|
18089
|
|uart|
|
UART Software Serial - Syncing two different sensors with start and stop bytes
|
2015-11-25T02:37:02.103
|
<p>I'm using 2 SRF02 sensors on the same Arduino board to attempt to have the transmitter only pulse the 40 KHz wave, while the receiver will be only taking a fake range, i.e. picking up a reading based on another transmission.</p>
<p>I've been using SoftwareSerial and need to know how to synchronize the time for the receiver to know when the transmitter sent the data. What I found is that I'm going to have to do this using start and stop bytes to set them in the same cycle.</p>
<p>How can I do this? </p>
<p>This is my current code: </p>
<pre><code>#include <SoftwareSerial.h>
SoftwareSerial mySerial(10,11); // RX, TX
void SendCmd(unsigned char address,unsigned char cmd) {
mySerial.write(address);
//set the address of SRF02(factory default is 0)
delayMicroseconds(100);
//serial data is fixed at 9600,N,8,2,so we need some time to create the second stop bit
mySerial.write(cmd);
//send the command to SRF02
delayMicroseconds(100);
//serial data is fixed at 9600,N,8,2,so we need some time to create the second stop bit
}
void setup(void) {
Serial.begin(9600);
mySerial.begin(9600);
Serial.println("SRF02 TEST!");
}
void loop(void) {
unsigned int reading;
SendCmd(0x00,0x5C);
//Transmit 8 cycle 40khz pulse from address 0x00 - transmitter
delay(70);
//time for SRF02 to measure the range
SendCmd(0x02,0x57);
//Get Fake Range at Address 0x02 - receiver
delay(10);
//wait for some time,let the Arduino receive 2 bytes data from the TX pin of SRF02
if(mySerial.available()>=2) {
//if two bytes were received
reading = mySerial.read()<<8;
//receive high byte (overwrites previous reading) and shift high byte to be high 8 bits
reading |= mySerial.read();
// receive low byte as lower 8 bits
Serial.print(reading);
// print the reading
Serial.println("cm");
//Serial.println("Time Sent: ");
//Serial.print(T_sent);
}
delay(250);
// wait a bit since people have to read the output :)
}
</code></pre>
|
<p>This is my updated code based on your suggestions, jwpat, although I did not understand your comment with <code>delay(70);</code> not being needed if I start conversion with <code>(2,0x5A)</code>. </p>
<pre><code>#include <SoftwareSerial.h>
SoftwareSerial mySerial(10,11); // RX, TX
void SendCmd(unsigned char address,unsigned char cmd)
{
mySerial.write(address);//set the address of SRF02(factory default is 0)
//delayMicroseconds(100);//serial data is fixed at 9600,N,8,2,so we need some time to creat the sencond stop bit
mySerial.write(cmd);//send the command to SRF02
//delayMicroseconds(100);//serial data is fixed at 9600,N,8,2,so we need some time to creat the sencond stop bit
}
void setup(void)
{
Serial.begin(9600);
mySerial.begin(9600);
Serial.println("SRF02 TEST!");
}
void loop(void)
{
unsigned long t3;
unsigned long t1=micros();//time tx command issued
SendCmd(0, 0x5C);//send pulse with transmitter
unsigned long t2=micros();//time rx command issued
SendCmd(2, 0x58);//listen for pulse
//SendCmd(2, 0x5A);
delay(70);//time for SRF02 to measure the range
//SendCmd(0x02,0x5E);
SendCmd(2,0x5E);//Get range
while(mySerial.available()>=2)//if two bytes were received
{
t3 = mySerial.read()<<8;//receive high byte (overwrites previous reading) and shift high byte to be high 8 bits
t3 |= mySerial.read();// receive low byte as lower 8 bits
unsigned long Tm = t3 + t2 - t1;//total amt of microseconds between pulse and reading
unsigned long Dist = (Tm/29); //converting microseconds to cm
Serial.print(Dist); // print the reading
Serial.println("cm");
//Serial.print(tm);
//Serial.println("ms");
}
delay(250); // wait a bit since people have to read the output :)
}
</code></pre>
<p>After running this code my results keep being the following values regardless of me shifting the distance between the sensors:
72cm <a href="https://i.stack.imgur.com/hXdBw.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/hXdBw.png" alt="enter image description here"></a></p>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.