I2C in arduino

Hi, I am trying to connect two arduino UNO together. Lets call one U1 and the other U2. U1 is master and U2 is slave. Now I want to attach a wave shield to U2 which is slave and operate it from U1. Is that possible? If it is possible, then can I use any pin to transmit and receive signal?? Cause in some forums they say that I2C is done by using digital pin 4 and 5. However, these pins are taken by wave shield. So please help me out in this.

Topic by Bam Boy   |  last reply


Rspberry PI I2C message control through Web portal

I need help to build web page which can control devices connected to raspberry pi through I2c . For example if i connected some DAC IC with raspberry pi . i i should able to adjust that DAC value from web. Please help us

Topic by Logen   |  last reply


Help... PCF8574T (Expanding "Nano's" Digital Outputs)

- When I saw my RGB Chromatograph clock my teacher built from a kit  I was so impressed with it I  jumped the gun & ordered the parts so I could make one with an arduino version, I never thought much about it, thats so simple I could do in a few hours no problem except I overlooked one simple thing.... This clock uses six 10mm RGB Leds, two for the hour, two for the minutes & two for the seconds, each led has 3 inputs & 1 ground, thats a total of 18 outputs,  thats not including a few other inputs used for status indicators, along with a few inputs for buttons, the problem is that a Nano doesnt have enough digital outputs & I completely overlooked that fact. Anyways I started looking for I/O expanders when I realized that I have a few 1602 displays & PCF8574T backpacks, I have heard some people claim that it can be used to provide an additional 16 digital outputs, if true then it that would resolve my issue very easy Has anyone done this? or example sketch how I could deploy the PCF8574 this way, for example a blink sketch that defines a pin on the PCF8574 as an outputs & turns on a LED connected to the pin Thank you much...

Question by rdlockrey   |  last reply


Glitchy I2C LCD (lines on the display)?

So, I am working on a little project with an Atmega328 and an 16x2 LCD. I have it wired up and when I went to test it with the "hello world" example, The LCD does work, but there are random lines on the display..  It's not the contrast or the code, and I checked the connections and it all seems ok. What might be causing my problem? 

Question by Dashing Rainbow Dash   |  last reply


I2C addresses > 63 are not usable with atTiny85?

Hi I have a big problem with addressing multiple attiny85-chips with I2C: For what I know the attiny uses 7-bit addresses for communication. I am using the TinyWireS lib, which works perfectly fine for me, untill I am reaching address: '64' which is '1000000' in binary. The highest usable address should be '1111111'. Here is the attiny85 datesheet. This is what happens: Slave: Attiny85: switches led on or off when msg is received over I2C. Slaveaddress: 64 #include #include #define output (4) #define I2C_SLAVE_ADDR (64) //works if I2C_SLAVE_ADDR < 64 void setup() {   TinyWireS.begin(I2C_SLAVE_ADDR);   pinMode(output, OUTPUT); } volatile bool state = LOW; void loop() {   byte msg = -1;   if(TinyWireS.available())     msg = TinyWireS.receive();   if(msg == 1)     state = HIGH;   else if(msg == 0)     state = LOW;   else if(msg == 2)     state = !state;   digitalWrite(output, state); } Master: Arduino pro mini: sendMsg(0, true); //works! led on chip: 64 switches on sendMsg(64, true); //fails! led on chip: 64 is off. #include #define DEVICE (64) //0 works! void setup() {     Wire.begin(); } void loop() {     sendMsg(1, DEVICE);     delay(2000);     sendMsg(0, DEVICE);     delay(2000); } void sendMsg(int msg, int device) {     Wire.beginTransmission(device);     Wire.write(msg);     Wire.endTransmission(); } Have you any idea how to solve this problem?

Question by DELETED_MakiY2   |  last reply


I2C to SPI BASIC code conversion?

 Hello all. Pretty daft and most likely simple sollution to those who know what they are doing I'm sure. I am building a 132 LED clock (60 for seconds, 60 for minutes and 12 for hours). I'm using a Picaxe 28X2 and will most likely be using 3 MAX7221's to display the LED's, 1 each for the hours, minutes and seconds. I'm currentlty using a DS1307 RTC module to keep time. Exposition over!  My question is, I am using open source code from a guy who made a clock using Pic 28X1, MAX7221 and DS1305 displaying on four 7-segment displays. now the differences between the Pic's with regard to coding I can handle, although I do have a 28X1. The fact that the DS1305 and 1307 use SPI and I2C respectively means that the differences between comms protocols are confusing the hell out of me.  Now please forgive the length of this question. Basically, I need some pointers as to whether it would be better to try and convert the code to use I2C for the RTC and stick with SPI for the MAX or should I just buy a DS1305 at almost £6 per chip and make my life a bit easier? I have already tried using the code with my 1307 but the 7-seg display I have just stays on the No2.  As for the differences in display type...well I'll come to that once I get the timing working.  If I've left anything out or you need more information then please let me know.  Here is the link to the clock schematic: http://tech-tut.com/wp-content/uploads/2008/08/real_time_clock_advanced_schematic.pdf    And the code is far too long to be pasted here I'm affraid and the file I originally got it from had converted it into word which pushed all the lines together. That was a fun few hours sorting that out! Thanks in advance

Question by LED Maestro   |  last reply


Does anybody know if the sensors from off brand wiimote cameras work with ardunio?

I've  been looking everywhere for a cheaper infrared camera.

Question by wkuace   |  last reply


Electronic Toolkit

I do some work with the FIRST Robotics kids and it is amazing to see what they are doing.  Big problem though seems to be a general lack of electrical test equipment.  They don't really have the money to buy oscilloscopes, function generators, CAN and I2C analyzers.   So I got one of the M3 Discovery boards from STmicro and it is really cool.  It has four 5MS A/Ds on it plus a whole host of other features(CAN, I2C, Serial etc.). http://www.st.com/web/en/catalog/tools/PF254044 So it got me thinking. Why couldn't we turn one of these chips into an "All-In-One" electrical toolkit and keep it cheap($50-$60, BOM ~$20).  It would be fairly easy to turnkey. I threw together some simple specs, what do people think. 1) Will supply general use drivers so a user can use the app or write their own. 2) Oscilloscope   a. Two Channel     i. 2MHZ of Analog Bandwidth per channel     ii. 10MS/s per channel     iii. Trigger on rising edge, falling edge, on-command, run-stop actions     iv. Datalogging for extended time periods at up to 10hz per channel (data stored directly to console),  maybe higher rate will  just have to see 3) Serial – 2 Ports   a. Multi selectable protocol w/slew control     i. RS232, RS422, RS485 4) CANBus – 1 port 5) I2C – 1 port 6) SPI  - 1 port 7) 8 Discrete User Selectable 8) Function Generator   a. Two Channel      i. 1MS/s small signal change      ii. 250kS/s full range change      iii. 0-3.3VDC buffered output  9) PWM - 4 Channels

Topic by ase4542   |  last reply



Integrating a sensor to arduino?

I want to know to integrate a sensor to arduino. I mean how to start and from where to start. I dont want to use existing libraries, I want to create my own. I know the working of sensors and and some other basic stuff.  I want to read a sensor data (for ex: ADXL345), I want to look into the datasheet and implement it. Please someone help in starting

Question by naveenkumarmn7   |  last reply


Building Audio System, Have Questions About ICs? Answered

So as the title states I want to design an audio system, I purchased an old shortwave radio someone gutted, but the case is in great shape and looks really cool, would make a killer looking amp.  So a little background, I want to make a stereo amp I can hook up several inputs to and my speakers; likely a turntable, iPod, radio, and whatever else I feel like.  The radio came with a nice little 5 position rotary switch for that.  The main problem I am facing is what ICs I want to use, and what order.  I have not dealt much with audio and at first I thought of buying a radio and just putting the guts into this unit, but I thought this would be a good project to dive into audio work.  You can't learn if you don't push your bounds a bit, am I right? The first IC question is about chips like the PT2322.  There are several I have looked at that use a microcontroller for control, and I am not against using an Arduino Micro in this unit, but I am unsure of how the acknowledgment bit works.  The data input seems to just be a shift register, data gets clocked in, then latched.  Data is fed in in 8 bit strings, but then it mentions an acknowledgement bit as a 9th bit.  Is this bit for the latch, or is there a 9th bit fed in before everything is latched?  Should it be hi or lo?  As well I was looking at the commands, several commands have 7 of their 8 bits written as a *, does this mean that those bits can be set hi or lo?  I am sure these aren't difficult questions and I glossed over something important in one of the many data sheets, and that I do not use these chips with any regularity, if ever, doesn't help either!  But I like that these ICs all seem to have a 3 band tone control and volume control built into them. If I were not to use an IC controlled by a microcontroller, I am looking at using a BA3812 for the tone controls, 5 band is a little more then I need, I really only wanted 3, not 2 but not more then 3.  Bass, treble and mid range.  But I could not find a 3 band IC without microcontroller inputs required for operation, and it was not for the lack of trying.  I can handle 5 bands though, however I am wondering, should I go preamp to equalizer to the main amp, or where would I wire in the BA3812?  This seems like a stupid question to me, I feel like an audiophile is going to come along and say, "You never put the equalizer after the preamp, it always goes here or there!" or something along those lines.  As well, regardless of where its going to get wired in, since I am doing stereo not mono, I assume I will need 2 BA3812's, but the datasheet supplies a circuit for 3 Chips as well.  Which would be suggested, 2 or 3?  I am wanting to control both left and right tone controls together, so using 5 pots instead of 10, and would also like to be able to have a balance control.  I didn't see anything about balance control in the BA3812 datasheet, would there be a good way of accomplishing that with these ICs or the use of a couple op amps maybe?  I didn't really look into balance, I should have before asking questions. For the preamp the LM1036 seemed like a good choice.  I was reading into preamps, and they seem more important for the turntable then anything else.  The way the grooves on a record are cut they boost the high frequencies so they don't fade awayat lower volumes or something like that.  Because of that a preamp that boosts bass and cuts treble is useful and improves sound quality when using turntables.  Should I use a preamp only for the turntable input or for all inputs?  If I adjust the equalizer for records is a preamp necessary or should I use the preamp and set it with trim pots to boost bass and cut treble a little, or should it be fully adjustable as well? As far as what to use for the final amplification I am at a bit of a loss.  A home theater system I have is 1500W and is adequately loud, but the system I have for my turntable right now think is only 250W I believe and it seems louder.  Never really understood wattages for "loudness"  or output on sound system.  I saw an IC (can't remember number, its a TDA though) dual 50W amplifier.  Not sure if 50W for each channel would be enough.  Advice would be helpful. As a side note, if I do go the route of a microcontroller, I found this NJW1186 with stereo input and 5.1 surround output which I thought would be cool. I really appreciate any help. Thank you

Question by KlockWork   |  last reply


Can the LP3943 source current as well, or only sink it? Answered

The link to the data sheet is here. All it talks about is sinking current, so my guess is yes.  I really wanted to use two of these to get a huge multiplexed array of LEDs, but one of them would need to be able to source the current, can it with the pins set high?  If not, are there other ICs like this that can do so? Thanks!

Question by mojofilta   |  last reply


can i use the S-3530A RTC with an arduino (no luck for i2c address from datasheet)? Answered

I found this rtc in a printer and i am having trouble setting the time on it. i would like to use it in place of a DS1307 but i dont know the i2c address of it ir how to set the time on it,. ANY help would be appreciated. datasheet: http://vk5bbs.ampr.org/pages/techdata/data/RTC/s3530a.pdf

Question by devicemodder   |  last reply


Connection Winstar WH1602B3-SLL-JWV 16x2 LCD VATN White on Black I2C Interface to Arduino UNO

Hello,I have some trouble with the connection of the Winstar I2C LCD to a Arduino Uno.Can someone advise me?In a pdf from Winstar there is a diagram (as attached), but I see a lot af pins that I don't know how to connect to a Arduino.Thank you very much for your help.Roland

Question by rolandzu   |  last reply


What are some low power displays for arduino communication?

I need a display that could show at least the date and/or time for an arduino clock.  I am looking for the one with the lowest power consumption possible, perhaps the kind found on digital watches?  (I don't know what those are called)  if possible the display should have spi or I2C communication, preferably I2C.   Any help would be awesome! Thanks  ~Dudes

Question by dudes   |  last reply


Can anyone please give me code to detect speed and display on LCD using I2C interface?

   I have a speed sensor which gives 8 pulse per revolution of wheel. I want to calculate the speed of the wheel and display it on an LCD using I2C interface. The LCD interface works fine and I can print anything on it. But I do not know the code to calculate the speed and display it on LCD.   Please help me and share with me a code that will calculate the speed based on 8 pulses/rev and display the speed on my LCD.

Question by edifiedsprit   |  last reply


using 2 x adafruit motor shield v2 in MATLAB

Hi, I set up an Arduino + adafruit motor shield v2 to control 4 x DC motors in a robot arm via MATLAB, which work fantastic. I mounted the robot arm on a 4WD base (each wheel has a separate DC motor), so now I have additional 4 more DC motors to control. I know the adafruit motor shield v2 is stackable, as long as you solder the I2C part on the second shield. I don't know if MATLAB supports 2 x adafruit motor shield v2 on top of Aurduino (2nd shield via I2c), to control 8 DC motors in total any advise or experience is highly appreciated

Question by Begginer2017   |  last reply


Is it possible to make a Beowulf Custer with Arduino?

Is it possible to make a small cluster computer using Arduinos? It has been done with Pi, but could it be made with breadboard Arduino? I read about I2C and it seems viable. Anyone had tried it yet? Awaiting some reply Trace

Question by Tanmay Das   |  last reply


S-3530A RTC and arduino

I found this rtc in a printer and i am having trouble setting the time on it. i would like to use it in place of a DS1307 but i dont know the i2c address of it ir how to set the time on it,. ANY help would be appreciated. datasheet: http://vk5bbs.ampr.org/pages/techdata/data/RTC/s3530a.pdf

Topic by devicemodder 


LED controlling with real time clock ?

Hello I am interfacing RTC with microcontroller  and LED. actually I have prototyping KIt (cortex m0). I only need c code. I want to control LED using real time clock via I2c pins         Set alarm for 5 second (automatically turn on LED for 5 second )         Set alarm for 3 minute (automatically turn on LED for 3 minute)         Set alarm for 1 hours (automatically turn on Led for 1 hours )         SCL connected with P3.5;         SDA connected with P3.1;         LED connected with P1.6         LED will read the data form ds1307 via i2c pins I did google searched but I did not find related to LED. I am not using LCD  can someone explain with small example. How to write c code for minute , hours , day

Question by vead 


Two arduino nano with oled check please help

Hi friends, I connected 2 arduino with i2c data, I'm doing the classic Led flashing, my question is, the master card in the project, counting from 1 to 100 counters, and initially the green LED is lit, when the counter is 80 yellow Led lights up green and 95 when yellow turns off and turns red, the system turns off. And this whole process is being copied to the sd card, the energy is cut off and the counter continues to be nosed when it is given again. Due to lack of memory the need for the second card was born. Now the Master is also on the slave card connected to the slave when it comes to burning operations (when the green LED is lit, the "system is running" while the yellow LED is running "maintenance approached" as the "service time", etc.) did the research but did not get a result. please help

Question by ErolT3 


how do I use the data from a ITG-3200 gyro? Answered

I have a ITG-3200 gyro on a breakoutboard from sparkfun. I got the I2C-communication working and I get a steady stream of data but I can't make anything sensible from it. Does Anyone have have experience with Gyros?

Question by janw   |  last reply


Does anybody know of a Potentiometer that can be set digitaly but operate passively?

I wonder if this technology exists. Imagine the following situation: During setup/calibration I can power the circuit and "tune" my potentiometer using some type of digital interface. (e.g. I2C) However, during operation the device is fully passive and will not have a source of power. Thus, the potentiometer would need to "remember" the settings and operate passively. Currently I use standard potentiometers, but tuning them manually is way too cumbersome and not practical. Ideas?

Question by Kapiau   |  last reply


Char Device Driver with Port Expansion using MCP23017?

I am new to Linux Kernel Development and I want to implement a Char device driver which handles Port expansion using a MCP23017 with a RaspberryPi (Raspbian Wheezy) using C. Here is the datesheet of mcp23017 A control for port expansion (MCP23017) is required. A less of a driver in the true sense, but more with porting functions in a driver.   The module is addressed via I2C. I need to implement the following functions in the driver: · Configuration of the I2C address · Configuration of the IOs · Configuration of Pull-Ups · Configuration of interrupts · Read / write the IOs It is important that up to 8 modules can be opened/operated simultaneously (8 is the max. possible number of addresses of the block). I have seen a number of examples in the internet and implemented a simple char device driver with init, open, read and write functions and also tested I2C operations for MCP23017. I have got a brief idea about a device driver but don't know how to further implement the functions. I would like to know/clarified about the following:     How does the dev_open work? How can I try to open a device through a linux command and check if the device is opened/ the number of times the device is opened through dmesg command?     I want 8 different modules to be opened simultaneously using the device driver and the Configuration of the MCP23017 IOs, Pullups and Interrupts. How is it done? Errors: /home/pi/i2c_gpio/mcp23017.c: In function ‘mcp23s08_direction_input’: /home/pi/i2c_gpio/mcp23017.c:269:9: error: implicit declaration of function      ‘gpiochip_get_data’ [-Werror=implicit-function-declaration] struct mcp23s08 *mcp = gpiochip_get_data(chip);      /home/pi/i2c_gpio/mcp23017.c: In function ‘mcp23s08_probe_one’: /home/pi/i2c_gpio/mcp23017.c:615:11: error: ‘struct gpio_chip’ has no         member  named ‘parent’ mcp->chip.parent = dev;                  /home/pi/i2c_gpio/mcp23017.c:681:2: error: implicit declaration of  function ‘gpiochip_add_data’ [-Werror=implicit-function-declaration] status = gpiochip_add_data(&mcp-;>chip, mcp); ^

Question by DELETED_MakiY2   |  last reply


Review of my first PCB design for a current meter shield?

I am completely new in designing circuits and PCBs and would appreciate your feedback on my first project. I want to measure the current flowing through an AC line using the ACS712 current sensor (IC1). The analog output (which is a proportional voltage between 0V and 5V) is converted using an ADS1115 (IC2). The digital signal is passed to an underlying Wemos D1 mini board via I2C, which contains an ESP8266 to process and send the data to a server. Furthermore, an AC/DC module (HLK-PM01) is mounted on the bottom side of the PCB to power the components.

Question by DELETED_MakiY2 


I need a way of measuring a 0-1000kHz signal (50% duty cycle square wave from a TSL237) with an arduino. Answered

I'm willing to use external hardware if it is cheap.I've tried using an interrupt base pulse accumulator but when the frequency becomes high the counter increments so fast that it stops the arduino from doing anything else (like stopping counting). Does anyone know of a nice easy solution to count frequency? Perhaps a fancy 8 pin DIP that talks i2c? I need to be senstive to the very low end of the frequency scale too, so just throwing a prescaler on will not solve this (afaik). Thanks.

Question by quatch   |  last reply


programming help

First of all, I am new to this. But for my CEIS course project I decided to program an rc vehicle because I thought it would be COOL! Now I am knee deep into the project and I am needing guidance.  So I am going to attempt to stack raspberry pi hats. One adafruit pwm for servos and the other adafruit pwm for dc and stepper motors. The first thing I done wrong was solder the gpio headers on backwards. Since I'm not too professional with a soldering iron I ended up making the drives of no use and ordered more. Before I done that, I got my pi camera working! Still need to program the pan/tilt servos. I have battery power, wiring, almost everything as far as hardware. Just not sure if I am headed in the right direction. I tried different things with python and the i2c but now when I start up the Kernel Module fails.  Any help will be great!

Topic by SMILEY4242 


Help on interfacing CAT35C104 Serial EEPROM to my arduino UNO please.? Answered

Hey, I'm still semi new to Arduino, but I can read/write to analog/digital pins and communicate via I2C and SPI with other devices and micro controllers, but those are more widely known and I have here with me a ton of 8 PIN DIP, CAT35C104 Serial EEPROM IC's.. And with all that EEPROM lying around I wanted to put it to some use. But I am still not an expert and don't know how to begin to interface it to my Arduino UNO R3.. :L Specifically it shows: CAT35C104 Serial EEPROM 4kb data storage, 512 x 8 bit registers, 256 x 16 bit Can anyone help me get this to work? I also have trouble with "opcodes" kinda confused.. right now I know the times it takes to read/write, and the clock frequency (1MHz) And the pin diagram.. Any help would be appreciated!!!!!

Question by Mudbud   |  last reply


Need help to spec a microcontroller.

​Hello! I am looking for a bit of guidance as I have limited knowledge in programming Microcontrollers...amateur experience covers a bit of Arduino and LabVIEW (mostly). My goal is to have an LCD display (Module size +- 65 x 40 mm, with SPI or I2C Comms, Monochromatic) to display small error message/codes and other information as for example temperature, speed, Test number and Timer. I do not know what would be the best Microcontroller to use that is off the shelf, that will still be in production for years to come and is "less complicated" to learn...from what I have read, perhaps the best microcontroller might be the Atmel just don't know what model (am open to other suggestions) Also there shall be 20 push buttons connected to the microcontroller. All that the microcontroller does is read the buttons as a byte and send it to another controller and receive information from that controller to know what information to display on the LCD. It shall also inform the controller of any error that it is experiencing.  I do hope that I am providing with clear and enough information so that someone could point me in the right direction.  Thank you in advance.

Topic by Art_Rob   |  last reply


How do I connect several Arduinos through RS485 with the SN75176 chip? Answered

Hello, I want to connect several Arduinos together in a star network (1 Master, several Slaves), but they're too far apart, so I can't use I2C. I researched a bit and found that I can use the serial protocol RS485 and that I can use the SN75176 or the MAX485 chips to do it. Being the MAX485 more expensive than the SN75176, I bought the latter. My problem is: now that I have the SN75176 (I have two, actually), what do I do? I have no clue whatsoever. I found some circuits for the MAX485, but I don't quite get how I should connect them to the Arduino.. Anyway, the chip I have is the SN75176... The only thing I find with Google is about DMX - for lights and stuff like that -, but I'm not interested in that. I just want several Arduinos to send data gathered from temperature and humidity sensors to another Arduino... Thank you very much. :)

Question by pedrotome   |  last reply


3 wire interface (GND, VCC, DATA)? Answered

Hi guys,   I'm trying to reverse the communications on a project I have at the moment which seems to be using a 3 wire serial interface (GND, VCC, DATA).  My goal would be to replicate the communications with an arduino or similar, however i'm not 100% sure what serial protocol it's using.   The device is using an Atmel ATMEGA168 and the pcb is covered in conformal coating, so I haven't had a whole lot of luck tracing the pins. I'm not overly aware of many one-wire communications protocols.  The datasheet says the ATMEGA supports various peripheral features, including SPI, USART, 2-wire serial (Philips I2C) (among others), however the GND, VCC, DATA configuration doesn't seem to fit with any of the supported protocols (i.e. there's no clock line and only a single data line).   The captures i'm getting seem to indicate that it's an 8-bit binary protocol.  I was going to try to decode it manually and attempt to reproduce it, however would be grateful if someone recognizes it and can point me in the right direction. Does anyone know any protocols / configurations this could be?  Example screenshot attached. Any help would be greatly appreciated!  Thanks!

Question by ikarus6   |  last reply


NodeMCU to NodeMCU communication

Dear All,I am really a newbie here playing with two NodeMCUs. I started out with basics and after a while I stepped into my actual project. The project is to display toilet status indicator. My plan is to pick up the data from PIR sensor and feed it to one NodeMCU and have another NodeMCU process the data on the other end of the room and display the status on and I2c 16 x 2 LCD. I was able to connect the PIR and LCD onto one NodeMCU and test it and things were fine. I am really looking for some help to use TCP/IP protocol to have the nodeMCUs communicate to each other.My basic code is as below:#include#include int sensor = 13;LiquidCrystal_I2C lcd(0x27, 16, 2);void setup(){ Serial.begin(115200);Wire.begin(D2, D1); pinMode(sensor, INPUT); pinMode(LED_BUILTIN, OUTPUT);lcd.begin(); }void loop (){ long state = digitalRead(13); if (state == HIGH){ Serial.println("Motion recognized"); lcd.setCursor(5, 0); lcd.print("RESTROOM IS"); lcd.setCursor(0, 1); lcd.print("OCCUPIED"); digitalWrite (LED_BUILTIN, LOW); delay(5000); lcd.clear(); } else { if (state == LOW); Serial.println("Motion Absent!"); lcd.setCursor(0, 1); lcd.print("NOW VACANT"); digitalWrite(LED_BUILTIN, HIGH); delay(5000); lcd.clear(); }}Thanks for any help you can provide or guide me to examples.

Question by BharatharajV 


How to make the GY-87 work probably ?

Hey, This my first question and ... action here with this new account :) My problem is I'm making a quad-copter, which needs some balance and no problem of adding some features like alt. measurement and so. I bought a GY-87 10DOF chip which combines 5 sensors :- MPU6050 Gyroscope MPU6050 Accelerometer BMP085 Barometer BMP085 Temperature sensor HMC5883L Magnometer I don't know yet how to make the quad-copter balance using the chip but I'm focusing now on making the chip work at all. After 7 hours of searching I could get a messy code using KALMAN filter to get the gyro and accel angels which worked fine eccept that the code combines the Z axis with the compass reading and I need to understand how to make every reading separate, which get us to the secong problem, the compass is stuck at 50.3 degrees, after reading i found that i must enable the I2C cuz both of the MPU and the HMC uses the same bus ways, I added a delay (100) ms to let the HMC get it's reading, i could make it work till I realized that the reading is not from 0- 360, it's between 200 and ... maybe 342 ! although making the BMP work was difficult a bit.. now my questions are :- -Understand how the gyro code works or at least add the Z axis of the the gyro not the compass -How to make the compass work probably Files:- https://drive.google.com/open?id=0BxGMyrtCX-KJVHB5S1luZ3VLeGM Libs:- https://drive.google.com/open?id=0BxGMyrtCX-KJcXZ6VlZmejRDR2c

Question by Mavrick23 


How to use Multiple mcp23017 chips with the adafruit mcp23017.h library?

I have been experimenting with I2C and the mcp23017 IO expander chip for my arduino ATMega2560 as I would rather use the IO on the arduino its self for other things I am just figuring out how to use the adafruit mcp23017.h library and cant figure out how to address multiple mcp23017 chips and how to use there pins individually this is the code from the button library that I editied. Here is the datesheet of mcp23017 I want to be able to address the individual chips and the pins I was not quite sure if in the setup that the pin modes for the IO go up sequentially from 0 past 15 if multiple chips are connected and addressed in code. For example if the first chip is addressed as 0x20 and the IO number count is from 0 - 15 if I added and addressed another chip as 0x21 will that count go from 0 - 15 to 0 - 31. ~ Edit if you could recommend or send a library that would be easier or could help please do. #include #include "Adafruit_MCP23017.h" //pin 1 and 0 are mcp pins not arduino IO pins Adafruit_MCP23017 mcp; void setup() {  mcp.begin();      // use default address 0 mcp.pinMode(0, INPUT); mcp.pinMode(1, OUTPUT); Serial.begin(9600); pinMode(13, OUTPUT);  // use the p13 LED as debugging } void loop() { // The LED will 'echo' the button digitalWrite(13, mcp.digitalRead(0)); //Writes pin 13 to the reading of pin    0 mcp.digitalWrite(1, mcp.digitalRead(0)); //Writes pin 1 to the reading of 0 if(mcp.digitalRead(1) == HIGH){ //if pin 1 == high serialprint led whent   high Serial.println("Led whent HIGH"); } }

Question by DELETED_MakiY2   |  last reply


Timer,Temprature & Humidity Based Relay Switching with Arduino Mega.? Answered

I am making a Climate Controler for my Green House. Please help me about Arduino code for Four Relay operation. relay1 will be high when Temp will rise higher then Temprature value defined and will low when reach under defined value. relay2 will be high when Humidity will rise higher then Humidity value defined and will low when reach under defined value  relay3 will be high for 10 Minutes in every 120 Minutes. relay4 will be high for 10 Minutes in every 120 Minutes.  I am Using DHT11 sensor with Mega2560 Board. Currently using this code. Its working for Temp & Humidty based Relay operation only. Need to add two relay with Timer based operation. System needs to check Humidity and Temprature value in every 10 minutes. Please Help.  I am very new for Arduino and making this for my personal use. #include #include #include /*-----( Declare objects )-----*/ // set the LCD address to 0x27 for a 20 chars 4 line display // Set the pins on the I2C chip used for LCD connections: //                    addr, en,rw,rs,d4,d5,d6,d7,bl,blpol LiquidCrystal lcd(20, 19, 18, 17, 16, 15); // Set the LCD I2C address dht11 DHT11; /*-----( Declare Constants, Pin Numbers )-----*/ #define DHT11PIN 22 #define RELAY1  6                        #define RELAY2  7                        #define RELAY3  4                        #define RELAY4  5 #define TempTarget 30 #define HUMTarget 50 void setup()   /*----( SETUP: RUNS ONCE )----*/ {   Serial.begin(9600); //(Remove all 'Serial' commands if not needed)   lcd.begin(20,2);         // initialize the lcd for 20 chars 4 lines, turn on backlight     // Print a message to the LCD.   //lcd.setCursor(0, 1);   lcd.print("SHOURYA's GARDEN");   // Initialise the Arduino data pins for OUTPUT   pinMode(RELAY1, OUTPUT);         pinMode(RELAY2, OUTPUT);   pinMode(RELAY3, OUTPUT);   pinMode(RELAY4, OUTPUT);   }/*--(end setup )---*/ void loop()   /*----( LOOP: RUNS CONSTANTLY )----*/ {   int chk = DHT11.read(DHT11PIN);   Serial.print   ("GARDEN DATA SENSING ");   switch (chk)   {     case 0: Serial.println(" OK"); break;     case -1: Serial.println("Checksum error"); break;     case -2: Serial.println("Time out error"); break;     default: Serial.println("Unknown error"); break;   }   lcd.setCursor(0, 1);   lcd.print("TempC=");   lcd.print((float)DHT11.temperature, 0);   Serial.print("Temperature (oC): ");   Serial.println((float)DHT11.temperature, 2);   //lcd.print(" F=");   //lcd.print(Fahrenheit(DHT11.temperature), 0);   //Serial.print("Temperature (oF): ");   //Serial.println(Fahrenheit(DHT11.temperature), 2);     lcd.print(" Hum=");   lcd.print((float)DHT11.humidity, 0);   lcd.print("%");   Serial.print("Humid(%): ");   Serial.println((float)DHT11.humidity, 2);    //Serial.print("Temperature (K): ");   //Serial.println(Kelvin(DHT11.temperature), 2);   //Serial.print("Dew Point (oC): ");   //Serial.println(dewPoint(DHT11.temperature, DHT11.humidity));   //Serial.print("Dew PointFast (oC): ");   //Serial.println(dewPointFast(DHT11.temperature, DHT11.humidity));        if (DHT11.temperature > TempTarget)       { Serial.println("Turning on Exaust Fan"); //lcd.print("Turning on Exaust Fan"); digitalWrite (RELAY1, HIGH); delay(1000);     }      if (DHT11.temperature < TempTarget)     { Serial.println("Turning Off Exaust Fan"); //lcd.print("Turning off Exaust Fan"); digitalWrite (RELAY1, LOW); delay(1000);     }       if (DHT11.humidity < HUMTarget)     { Serial.println("Turning on HUMIDIFIER"); //lcd.print("Turning on HUMIDIFIER"); digitalWrite (RELAY2, HIGH); delay(1000);     }      if (DHT11.humidity > HUMTarget)     { Serial.println("Turning Off HUMIDIFIER"); //lcd.print("Turning off HUMIDIFIER"); digitalWrite (RELAY2, LOW); delay(1000);     }       digitalWrite(RELAY3,HIGH);           // Turns ON Relays 3    digitalWrite(RELAY4,HIGH);           // Turns ON Relays 4    delay(10*1000);     digitalWrite(RELAY3,LOW);          // Turns Relay Off    digitalWrite(RELAY4,LOW);          // Turns Relay Off   }/* --(end main loop )-- */ /*-----( Declare User-written Functions )-----*/ // //Celsius to Fahrenheit conversion double Fahrenheit(double celsius) {         return 1.8 * celsius + 32; } //Celsius to Kelvin conversion double Kelvin(double celsius) {         return celsius + 273.15; } // dewPoint function NOAA // reference: http://wahiduddin.net/calc/density_algorithms.htm double dewPoint(double celsius, double humidity) {         double A0= 373.15/(273.15 + celsius);         double SUM = -7.90298 * (A0-1);         SUM += 5.02808 * log10(A0);         SUM += -1.3816e-7 * (pow(10, (11.344*(1-1/A0)))-1) ;         SUM += 8.1328e-3 * (pow(10,(-3.49149*(A0-1)))-1) ;         SUM += log10(1013.246);         double VP = pow(10, SUM-3) * humidity;         double T = log(VP/0.61078);   // temp var         return (241.88 * T) / (17.558-T); } // delta max = 0.6544 wrt dewPoint() // 5x faster than dewPoint() // reference: http://en.wikipedia.org/wiki/Dew_point double dewPointFast(double celsius, double humidity) {         double a = 17.271;         double b = 237.7;         double temp = (a * celsius) / (b + celsius) + log(humidity/100);         double Td = (b * temp) / (a - temp);         return Td; } /* ( THE END ) */

Question by achauhan13   |  last reply


why does the lcd shows the old value after I make the power off ?

Hello, my project is a Real Time Digital Clock I'm using LCD 16x 2 with DS1307 connected with pic18f4550 when i burn the code to the circuit it shows the time correctly but when i make the power off then make it ON it shows the previous code which is not correctly ! How can i fix this ? shall i use battery for the DS1307 ? what do you suggest from me ? this is the code written in mikroc  : #ifndef DS1307 #define DS1307 0xD0 #endif // Software I2C connections sbit Soft_I2C_Scl at RB1_bit; sbit Soft_I2C_Sda at RB0_bit; sbit Soft_I2C_Scl_Direction at TRISB1_bit; sbit Soft_I2C_Sda_Direction at TRISB0_bit; // End Software I2C connections sbit LCD_RS at RB3_bit; sbit LCD_RW at RD0_bit; sbit LCD_EN at RB2_bit; sbit LCD_D4 at RD1_bit; sbit LCD_D5 at RD2_bit; sbit LCD_D6 at RD3_bit; sbit LCD_D7 at RD4_bit; sbit LCD_RS_Direction at TRISB3_bit; sbit LCD_RW_Direction at TRISD0_bit; sbit LCD_EN_Direction at TRISB2_bit; sbit LCD_D4_Direction at TRISD1_bit; sbit LCD_D5_Direction at TRISD2_bit; sbit LCD_D6_Direction at TRISD3_bit; sbit LCD_D7_Direction at TRISD4_bit; char i; unsigned char sec, min1, hr, week_day, day, mn, year; char *txt, tnum[4]; // for some other testing char txtSec[10]; char txtMin[10]; char txtHour[10]; char txtWeekDay[10]; char txtDay[10]; char txtMn[10]; char txtYear[5]; char txtDisplay[39]; // for some testing int intSec, intMin, intHour, intWeekDay, intMn, intDay, intYear; void Read_Time(char *sec, char *min, char *hr, char *week_day, char *day, char *mn, char *year) {         Soft_I2C_Start();         Soft_I2C_Write(DS1307);         Soft_I2C_Write(0x00);         Soft_I2C_Start();         Soft_I2C_Write(0xD1);     //MAKE SURE D1 IS ADDRSS OF PIC18F4550         *sec =Soft_I2C_Read(1);         *min =Soft_I2C_Read(1);         *hr =Soft_I2C_Read(1);         *week_day =Soft_I2C_Read(1);         *day =Soft_I2C_Read(1);         *mn =Soft_I2C_Read(1);         *year =Soft_I2C_Read(0);         Soft_I2C_Stop(); } /* void Transform_Time(char  *sec, char *min, char *hr, char *week_day, char *day, char *mn, char *year) {         *sec  =  ((*sec & 0x70) >> 4)*10 + (*sec & 0x0F);         *min  =  ((*min & 0xF0) >> 4)*10 + (*min & 0x0F);         *hr   =  ((*hr & 0x30) >> 4)*10 + (*hr & 0x0F);         *week_day =(*week_day & 0x07);         *day  =  ((*day & 0xF0) >> 4)*10 + (*day & 0x0F);         *mn   =  ((*mn & 0x10) >> 4)*10 + (*mn & 0x0F);         *year =  ((*year & 0xF0)>>4)*10+(*year & 0x0F); }  **/ //-------------------- Formats date and time void Transform_Time() {   *sec  =  ((*sec & 0xF0) >> 4)*10 + (*sec & 0x0F);  // Transform seconds   *min  =  ((*min & 0xF0) >> 4)*10 + (*min & 0x0F);  // Transform months *hr    =  ((*hr & 0xF0)  >> 4)*10  + (*hr & 0x0F);    // Transform hours   *year    =   (*year & 0xC0) >> 6;                             // Transform year   *day     =  ((*day  & 0x30) >> 4)*10    + (*day  & 0x0F);       // Transform day *mn   =  ((*mn & 0x10)  >> 4)*10 + (*mn & 0x0F);     // Transform month } void Write_Time() {         Soft_I2C_Start();          // issue start signal         Soft_I2C_Write(DS1307);       // address DS1307         Soft_I2C_Write(0);            // start from word at address (REG0)         Soft_I2C_Write(0x40);         // write 17 to hours word (24-hours mode)(REG2) (sec)*         Soft_I2C_Write(0x23);         // write 2 - Monday (REG3)   ,( min ) *         Soft_I2C_Write(0x14);         // write 4 to date word (REG4)  (hr) *         Soft_I2C_Write(0x03);         // write 5 (May) to month word (REG5) (day)*         Soft_I2C_Write(0x14);         // write 01 to year word (REG6) (year)*         Soft_I2C_Write(0x05);         Soft_I2C_Write(0x13);         Soft_I2C_Stop();           // issue stop signal         Soft_I2C_Start();          // issue start signal         Soft_I2C_Write(DS1307);       // address DS1307         Soft_I2C_Write(0);            // start from word at address 0         Soft_I2C_Write(0);            // write 0 to REG0 (enable counting + 0 sec)         Soft_I2C_Stop();          // issue stop signal } void Transform_Time(char  *sec, char *min, char *hr, char *week_day, char *day, char *mn, char *year) {         *sec  =  ((*sec & 0x70) >> 4)*10 + (*sec & 0x0F);         *min  =  ((*min & 0xF0) >> 4)*10 + (*min & 0x0F);         *hr   =  ((*hr & 0x30) >> 4)*10 + (*hr & 0x0F);         *week_day =(*week_day & 0x07);         *day  =  ((*day & 0xF0) >> 4)*10 + (*day & 0x0F);         *mn   =  ((*mn & 0x10) >> 4)*10 + (*mn & 0x0F);         *year =  ((*year & 0xF0)>>4)*10+(*year & 0x0F); } /* void Display_Time() {         switch(week_day)         {                 case 1: txt="Sun"; break;                 case 2: txt="Mon"; break;                 case 3: txt="Tue"; break;                 case 4: txt="Wed"; break;                 case 5: txt="Thu"; break;                 case 6: txt="Fri"; break;                 case 7: txt="Sat"; break;         }   **/         Lcd_Chr(1, 6, (day / 10)   + 48);    // Print tens digit of day variable    Lcd_Chr(1, 7, (*day % 10)   + 48);    // Print oness digit of day variable    Lcd_Chr(1, 9, (*mn / 10) + 48);    Lcd_Chr(1,10, (month % 10) + 48);    Lcd_Chr(1,15,  year        + 48);    // Print year variable  (start from year 2010)    Lcd_Chr(2, 6, (hours / 10)   + 48);    Lcd_Chr(2, 7, (hours % 10)   + 48);    Lcd_Chr(2, 9, (minutes / 10) + 48);    Lcd_Chr(2,10, (minutes % 10) + 48);    Lcd_Chr(2,12, (seconds / 10) + 48);    Lcd_Chr(2,13, (seconds % 10) + 48); }         Lcd_Init();         Lcd_Cmd(_LCD_CLEAR);               // Clear display         Lcd_Cmd(_LCD_CURSOR_OFF);          // Cursor off         Lcd_Out(1,1,txt);         Lcd_Chr(1, 6, (day / 10)   + 48);    // Print tens digit of day variable         Lcd_Chr(1, 7, (day % 10)   + 48);    // Print oness digit of day variable         Lcd_Chr(1,8,'.');         Lcd_Chr(1, 9, (mn / 10) + 48);         Lcd_Chr(1,10, (mn % 10) + 48);         Lcd_Chr(1,11,'.');         Lcd_Chr(1,12,  (year / 10)  + 48);          // Print year vaiable + 8 (start from year 2008)         Lcd_Chr(1,13,  (year % 10)  + 48);         txt = "Time";         Lcd_Out(2,1,txt);         Lcd_Chr(2, 6, (hr / 10)   + 48);         Lcd_Chr(2, 7, (hr % 10)   + 48);         Lcd_Chr(2,8,':');         Lcd_Chr(2, 9, (min / 10) + 48);         Lcd_Chr(2,10, (min % 10) + 48);         Lcd_Chr(2,11,':');         Lcd_Chr(2,12, (sec / 10) + 48);         Lcd_Chr(2,13, (sec % 10) + 48);         Lcd_Cmd(_LCD_CURSOR_OFF); } void Init_Main_Simple() {         ADCON1 = 0x0F; // page 268, disable analaog        // CMCON = 0x07;        // INTCON2 = 0x80; // disable pull up in port b         // clears internal latches         LATB = 0x03; // enable internal pull ups         LATA = 0x00;         LATC = 0x00;         LATD = 0x00;         LATE = 0x00;         // Make all outputs         TRISA = 0x00;         TRISB = 0x03;         TRISC = 0x00;         TRISD = 0x00;         TRISE = 0x00;         Lcd_Init();                // Initialize LCD         Lcd_Cmd(_LCD_CLEAR);       // Clear LCD display         Lcd_Cmd(_LCD_CURSOR_OFF);  // Turn cursor off         Soft_I2C_Init();                        // initialize I2C         Lcd_Out(1,1,"Time & Date"); } void main() {            Delay_ms(500);        Init_Main_Simple();        //Write_Time();         //Delay_ms(100);         while (1) {                 Read_Time(&sec;,&min1;,&hr;,&week;_day,&day;,&mn;,&year;);      // read time from RTC(DS1307)                 Transform_Time(&sec;,&min1;,&hr;,&week;_day,&day;,&mn;,&year;); // format date and time                 Display_Time(sec, min1, hr, week_day, day, mn, year);                 Delay_ms(1000);         } } Thanks

Question by dndanah1   |  last reply


wemos d1 mini blynk? display temperature&humidity?

this is my code and it works to display c&% on display and blynk app and it notifies me when it starts and run time, is there a way to display runtime/uptime on the display and should i remove anything? maybe add in code to send email when offline for more than 5 minutes? why does the screen go black when it updates? what other data can i display on the screen? it will be used to monitor server room temperature, thanks #include #include #include #include "Adafruit_SSD1306.h" #include #include #include #define OLED_RESET 0  // GPIO0 Adafruit_SSD1306 display(OLED_RESET); #define BLYNK_PRINT Serial #define DHTPIN D4 #define DHTTYPE DHT22  DHT dht(DHTPIN, DHTTYPE); // You should get Auth Token in the Blynk App. // Go to the Project Settings (nut icon). char auth[] = ""; // Your WiFi credentials. // Set password to "" for open networks. char ssid[] = ""; char pass[] = ""; BlynkTimer timer; void notifyUptime() {   long uptime = millis() / 60000L;   // Actually send the message.   // Note:   //   We allow 1 notification per 15 seconds for now.   Blynk.notify(String("Running for ") + uptime + " minutes."); } void sendSensor() {   float h = dht.readHumidity();   float t = dht.readTemperature(); // or dht.readTemperature(true) for Fahrenheit   if (isnan(h) || isnan(t)) {     Serial.println("where is my DHT sensor!");     return;   }   // You can send any value at any time.   // Please don't send more that 10 values per second.   Blynk.virtualWrite(V5, h);   Blynk.virtualWrite(V6, t); } void setup() {   // Debug console   Serial.begin(9600);   Blynk.begin(auth, ssid, pass);   // You can also specify server:   //Blynk.begin(auth, ssid, pass, "blynk-cloud.com", 8442);   //Blynk.begin(auth, ssid, pass, IPAddress(192,168,1,100), 8442);   dht.begin();   // Notify immediately on startup   Blynk.notify("Device started");   // Setup a function to be called every minute   timer.setInterval(60000L, notifyUptime);     // Setup a function to be called every second   timer.setInterval(1000L, sendSensor); } void loop() {   Blynk.run();   timer.run();   Serial.begin(115200);   dht.begin();   // by default, we'll generate the high voltage from the 3.3v line internally! (neat!)   display.begin(SSD1306_SWITCHCAPVCC, 0x3C);  // initialize with the I2C addr 0x3C (for the 64x48)   display.display();   delay(5000);   // Efface l'écran et positionne le curseur dans le coin supérieur gauche - clear display and set cursor on the top left corner   display.clearDisplay();   display.setTextSize(2);   display.setTextColor(WHITE);   display.setCursor(0,0);   float h = dht.readHumidity();   float t = dht.readTemperature();   float f = dht.readTemperature(true);   float bat = ESP.getVcc();// / 1024;   // Check if any reads failed and exit early (to try again).   if (isnan(h) || isnan(t) || isnan(f)) {     Serial.println("where is DHT sensor!");     return;   }     // Température en Celcius - Temperature in Celcius // display.println("Temp.");   display.print(t);   display.println(" c");   // Humidité en % - Humidity in % // display.println("Humidity"); //display.setTextSize(1);   display.print(h);   display.print(" %");   display.display(); }

Question by turbiny 


I have a problem in this code for Arduino UNO , Can you help me?

#include #include #define SOL_ADC A0     // Solar panel side voltage divider is connected to pin A0 #define BAT_ADC A1    // Battery side voltage divider is connected to pin A1 #define CURRENT_ADC A2  // ACS 712 current sensor is connected to pin A2 #define TEMP_ADC A3   // LM 35 Temperature is connected to pin A3 #define AVG_NUM 10    // number of iterations of the adc routine to average the adc readings #define BAT_MIN 10.5  // minimum battery voltage for 12V system #define BAT_MAX 15.0  // maximum battery voltage for 12V system #define BULK_CH_SP 14.4 // bulk charge set point for sealed lead acid battery // flooded type set it to 14.6V #define FLOAT_CH_SP 13.6  //float charge set point for lead acid battery #define LVD 11.5          //Low voltage disconnect setting for a 12V system #define PWM_PIN 3         // pin-3 is used to control the charging MOSFET //the default frequency is 490.20Hz #define LOAD_PIN 2       // pin-2 is used to control the load #define BAT_RED_LED 5 #define BAT_GREEN_LED 6 #define BAT_BLUE_LED 7 #define LOAD_RED_LED 8 #define LOAD_GREEN_LED 9 //-------------------------------------------------------------------------------------------------------------------------- ///////////////////////DECLARATION OF ALL BIT MAP ARRAY FOR FONTS//////////////////////////////////////////////////////////////// //-------------------------------------------------------------------------------------------------------------------------- byte solar[8] = //icon for solar panel {   0b11111,0b10101,0b11111,0b10101,0b11111,0b10101,0b11111,0b00000 }; byte battery[8] =  //icon for battery {   0b01110,0b11011,0b10001,0b10001,0b10001,0b10001,0b10001,0b11111 }; byte energy[8] =  // icon for power {   0b00010,0b00100,0b01000,0b11111,0b00010,0b00100,0b01000,0b00000 }; /*byte alarm[8] =  // icon for alarm { 0b00000,0b00100,0b01110,0b01110,0b01110,0b11111,0b00000,0b00100 };*/ byte temp[8] = //icon for termometer { 0b00100,0b01010,0b01010,0b01110,0b01110,0b11111,0b11111,0b01110 }; byte charge[8] = // icon for battery charge {   0b01010,0b11111,0b10001,0b10001,0b10001,0b01110,0b00100,0b00100, }; byte not_charge[8]= {   0b00000,0b10001,0b01010,0b00100,0b01010,0b10001,0b00000,0b00000, }; //-------------------------------------------------------------------------------------------------------------------------- ///////////////////////DECLARATION OF ALL GLOBAL VARIABLES////////////////////////////////////////////////////////////////// //-------------------------------------------------------------------------------------------------------------------------- float solar_volt=0; float bat_volt=0; float load_current=0; int temperature=0; int temp_change=0; float system_volt=0; float bulk_charge_sp=0; float float_charge_sp=0; float charge_status=0; float load_status=0; float error=0; float Ep=0; int duty =0; float lvd; float msec=0; float last_msec=0; float elasped_msec=0; float elasped_time=0; float ampSecs = 0; float ampHours=0; float watts=0; float wattSecs = 0; float wattHours=0; // Set the pins on the I2C chip used for LCD connections: //                    addr, en,rw,rs,d4,d5,d6,d7,bl,blpol LiquidCrystal_I2C lcd(0x27, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE);  // Set the LCD I2C address // In my case 0x27 //******************************************************* MAIN PROGRAM START ************************************************ void setup() { Serial.begin(9600); pinMode(BAT_RED_LED,OUTPUT); pinMode(BAT_GREEN_LED,OUTPUT); pinMode(BAT_BLUE_LED,OUTPUT); pinMode(LOAD_RED_LED ,OUTPUT); pinMode(LOAD_GREEN_LED,OUTPUT); pinMode(PWM_PIN,OUTPUT); pinMode(LOAD_PIN,OUTPUT); digitalWrite(PWM_PIN,LOW);  // default value of pwm duty cycle digitalWrite(LOAD_PIN,LOW);  // default load state is OFF lcd.begin(20,4);   // initialize the lcd for 16 chars 2 lines, turn on backlight lcd.backlight(); // finish with backlight on  lcd.createChar(1,solar); lcd.createChar(2, battery); lcd.createChar(3, energy); //lcd.createChar(4,alarm); lcd.createChar(5,temp); lcd.createChar(6,charge); lcd.createChar(7,not_charge); lcd.clear(); } void loop() { read_data();             // read different sensors data from analog pin of arduino system_voltage();        // detect the system voltage according to battery voltage setpoint();      // decide the charge set point according to system voltage charge_cycle();         // pwm charging of battery power();                // calculate the load power and energy load_control();         //control the load led_indication();       // led indica print_data();            // print in serial monitor lcd_display();           // lcd display } //************************************************************ PROGRAM END ************************************************* //------------------------------------------------------------------------------------------------------ ////////////////// READS AND AVERAGES THE ANALOG INPUTS (SOLRAR VOLTAGE,BATTERY VOLTAGE)//////////////// //------------------------------------------------------------------------------------------------------ int read_adc(int adc_parameter) {     int sum = 0;   int sample ;   for (int i=0; i   {                                        // loop through reading raw adc values AVG_NUM number of times      sample = analogRead(adc_parameter);    // read the input pin      sum += sample;                        // store sum for averaging     delayMicroseconds(50);              // pauses for 50 microseconds    }   return(sum / AVG_NUM);                // divide sum by AVG_NUM to get average and return it } //------------------------------------------------------------------------------------------------------------- ////////////////////////////////////READ THE DATA////////////////////////////////////////////////////////////// //------------------------------------------------------------------------------------------------------------- void read_data(void) {     //5V = ADC value 1024 => 1 ADC value = (5/1024)Volt= 0.0048828Volt     // Vout=Vin*R2/(R1+R2) => Vin = Vout*(R1+R2)/R2   R1=100 and R2=20      solar_volt = read_adc(SOL_ADC)*0.00488*(120/20);      bat_volt   = read_adc(BAT_ADC)*0.00488*(120/20);            load_current = (read_adc(CURRENT_ADC)*.0488 -25);      temperature = read_adc(TEMP_ADC)*0.00488*100;        }   //------------------------------------------------------------------------------------------------------------ /////////////////////////////////POWER AND ENERGY CALCULATION ////////////////////////////////////////////// //------------------------------------------------------------------------------------------------------------ void power(void) { msec = millis(); elasped_msec = msec - last_msec; //Calculate how long has past since last call of this function elasped_time = elasped_msec / 1000.0; // 1sec=1000 msec watts = load_current * bat_volt; //Watts now ampSecs = (load_current*elasped_time); //AmpSecs since last measurement wattSecs = ampSecs * bat_volt; //WattSecs since last measurement ampHours = ampHours + ampSecs/3600; // 1 hour=3600sec //Total ampHours since program started wattHours = wattHours + wattSecs/3600; // 1 hour=3600sec //Total wattHours since program started last_msec = msec; //Store 'now' for next time } //------------------------------------------------------------------------------------------------------------ /////////////////////////////////PRINT DATA IN SERIAL MONITOR///////////////////////////////////////////////// //------------------------------------------------------------------------------------------------------------   void print_data(void)   {     delay(100);     Serial.print("Solar Panel Voltage: ");     Serial.print(solar_volt);     Serial.println("V");     Serial.print("Battery Voltage: ");     Serial.print(bat_volt);     Serial.println("V");     Serial.print("Syestem Voltage: ");     Serial.print(system_volt);     Serial.println("V");     Serial.print("Charge Set Point:");     Serial.println(bulk_charge_sp);     Serial.print("Temperature:");     Serial.print(temperature);     Serial.println("C");     Serial.print("Load Current: ");     Serial.print(load_current);     Serial.println("A");     Serial.print("Power: ");     Serial.print(watts);     Serial.println("W");     Serial.print("Energy: ");     Serial.print(wattHours);     Serial.println("WH");     Serial.print("Duty Cycle :");     if (charge_status==1)     {     Serial.println("99%");     Serial.println("BULK CHARGING");     }     else if (charge_status==2)     {     Serial.print(Ep);     Serial.println("%");     Serial.println("FLOAT CHARGING");     }     else     {     Serial.println("0%");     Serial.println("NOT CHARGING");     }     if(load_status==1)     {      Serial.println("LOAD IS CONNECTED");     }     else     {      Serial.println("LOAD IS DISCONNECTED");       }        Serial.println("***************************"); } //---------------------------------------------------------------------------------------------------------------------- //////////////////////////////////SYSTEM VOLTAGE AUTO DETECT /////////////////////////////////////////////////////////// //---------------------------------------------------------------------------------------------------------------------- void system_voltage(void) {   if ((bat_volt >BAT_MIN) && (bat_volt < BAT_MAX))   {      system_volt = 12;   }   /*   else if  ((bat_volt > BAT_MIN*2 ) && (bat_volt < BAT_MAX*2))   {     system_volt=24;   }*/   else if ((bat_volt > BAT_MIN/2 ) && (bat_volt < BAT_MAX/2))   {     system_volt=6;   }   } //--------------------------------------------------------------------------------------------------------------------------- ////////////////////////////////////CHARGE SET POINT /////////////////////////////////////////////////////////////////////// //--------------------------------------------------------------------------------------------------------------------------- void setpoint(void) {   temp_change =temperature-25.0; // 25deg cel is taken as standard room temperature // temperature compensation = -5mv/degC/Cell   // If temperature is above the room temp ;Charge set point should reduced   // If temperature is bellow the room temp ;Charge set point should increased   if(system_volt ==12)   {      bulk_charge_sp = BULK_CH_SP-(0.030*temp_change) ;      float_charge_sp=FLOAT_CH_SP-(0.030*temp_change) ;      lvd =LVD;   }   else if(system_volt ==6)   {      bulk_charge_sp = (BULK_CH_SP/2)-(0.015*temp_change) ;      float_charge_sp= (FLOAT_CH_SP/2)-(0.015*temp_change) ;      lvd=LVD/2;   }   /*   else if (system_volt == 24)   {    bulk_charge_sp = (BULK_CH_SP*2)-(0.060*temp_change) ;    float_charge_sp= (FLOAT_CH_SP*2)-(0.060*temp_change) ;    lvd=LVD*2;   }   */   } //-------------------------------------------------------------------------------------------------------------------------------- ///////////////////////////////////////////////////PWM CHARGE CYCLE @500 HZ ////////////////////////////////////////////////// //------------------------------------------------------------------------------------------------------------------------------- void charge_cycle(void) {   if (solar_volt > bat_volt && bat_volt <= bulk_charge_sp)   {         if (bat_volt <= float_charge_sp) // charging start   {       charge_status = 1; // indicate the charger is in BULK mode      duty= 252.45;      analogWrite(PWM_PIN,duty); // 99 % duty cycle // rapid charging           }   else if (bat_volt >float_charge_sp && bat_volt <= bulk_charge_sp)   {         charge_status = 2; // indicate the charger is in FLOAT mode       error  = (bulk_charge_sp - bat_volt);      // duty cycle reduced when the battery voltage approaches the charge set point       Ep= error *100 ; //Ep= error* Kp // Assume  Kp=100             if(Ep < 0)        {         Ep=0;         }       else if(Ep>100)         {          Ep=100;         }       else if(Ep>0 && Ep <=100) // regulating        {          duty = (Ep*255)/100;        }        analogWrite(PWM_PIN,duty);    } }    else    {    charge_status=0;  // indicate the charger is OFF    duty=0;    analogWrite(PWM_PIN,duty);    } } //---------------------------------------------------------------------------------------------------------------------- /////////////////////////////////////////////LOAD CONTROL///////////////////////////////////////////////////// //----------------------------------------------------------------------------------------------------------------------    void load_control() { if (solar_volt < 5  ) // load will on when night {   if(bat_volt >lvd)   // check if battery is healthy   {   load_status=1;   digitalWrite(LOAD_PIN, HIGH); // load is ON   }   else if(bat_volt < lvd)   {     load_status=0;    digitalWrite(LOAD_PIN, LOW); //load is OFF   } } else // load will off during day {    load_status=0;    digitalWrite(LOAD_PIN, LOW); } } //------------------------------------------------------------------------------------------------- //////////////////////////LED INDICATION//////////////////////////////////// //------------------------------------------------------------------------------------------------- void led_indication(void) {   battery_led();           //Battery status led indication   load_led();              //Load led indication } //---------------------------------------------------------------------------------------------------------------------- /////////////////////////////////////////////BATTERY LED INDICATION///////////////////////////////////////////////////// //---------------------------------------------------------------------------------------------------------------------- void battery_led(void) {      if( (bat_volt > system_volt) && ( bat_volt   {         leds_off_all();       digitalWrite(BAT_GREEN_LED,LOW);  // battery voltage is healthy   }   else if(bat_volt >= bulk_charge_sp)   {       leds_off_all();       digitalWrite(BAT_BLUE_LED,LOW);  //battery is fully charged   }    else if(bat_volt < system_volt)   {       leds_off_all();       digitalWrite(BAT_RED_LED,LOW);  // battery voltage low   } } //---------------------------------------------------------------------------------------------------------------------- /////////////////////////////////////////////LOAD LED INDICATION///////////////////////////////////////////////////// //----------------------------------------------------------------------------------------------------------------------      void load_led()   {     if(load_status==1)     {       digitalWrite(LOAD_GREEN_LED,HIGH);     }     else if(load_status==0)     {       digitalWrite(LOAD_RED_LED,HIGH);     }    } //------------------------------------------------------------------------------------------------------ //////////////////////// TURN OFF ALL THE LED/////////////////////////////////////////////////////////// //------------------------------------------------------------------------------------------------------ void leds_off_all(void) {     digitalWrite(BAT_RED_LED,HIGH);   digitalWrite(BAT_GREEN_LED,HIGH);   digitalWrite(BAT_BLUE_LED,HIGH);   digitalWrite(LOAD_RED_LED, LOW);   digitalWrite(LOAD_GREEN_LED, LOW); } //------------------------------------------------------------------------------------------------------ //////////////////////// LCD DISPLAY/////////////////////////////////////////////////////////// //------------------------------------------------------------------------------------------------------ void lcd_display() { lcd.setCursor(0, 0); lcd.write(1); lcd.setCursor(2, 0); lcd.print(solar_volt); lcd.print("V"); lcd.setCursor(14, 0); lcd.write(5); lcd.setCursor(16, 0); lcd.print(temperature); lcd.write(0b11011111); lcd.print("C"); lcd.setCursor(0,1); lcd.write(2); lcd.setCursor(2, 1); lcd.print(bat_volt); lcd.print("V"); lcd.setCursor(14, 1); lcd.write(2); if((charge_status==1) | (charge_status== 2)) { lcd.write(6); } else { lcd.write(7); } lcd.setCursor(0,2); lcd.write(3); lcd.setCursor(2,2); lcd.print(load_current); lcd.print("A"); lcd.setCursor(13,2); lcd.print(watts); lcd.print("W"); lcd.setCursor(0,3); lcd.print("Energy:"); lcd.print(wattHours); lcd.print("WH");      }

Question by Fares Mareai   |  last reply


Im repurposing my atx power supply to be a bench Psu. I need help with code please?

In this project. I want to use an arduino mega, 2 lcds, and 6 acs712 current sensing modules and 2 Lm2596 dc step up/down module The set up I have in mind is like so; arduino is powered by ATX stand by power (IF possible) there is a push button which turns on the programing to start the monitoring and also grounds the ATX and GReen wire to supply power to all the rails. This set up will calculate Voltage and current printting them on the lcd's. The constant voltages will be printed on on lcd and the variable voltages on the other lcd. Ive written most of the code. I just want it to make sense. I've added a picture, which my project is based on.. the difference are, im not using I2c bus for lcd, im measuring current, and im printing info on two different lcds. thanks for the help. here is the code #include #define PWROK_PIN 4 // change to w.e pin i end up using connected to green? investigate #define PWRBTN 2 // closing push buttom connection makes it high #define PWRTRANS 6 /*-----( Declare objects )-----*/ // Variables will change: int PWRSTATE = HIGH;         // the current state of the output pin int buttonState;             // the current reading from the input pin int lastButtonState = LOW;   // the previous reading from the input pin // the following variables are long's because the time, measured in miliseconds, // will quickly become a bigger number than can be stored in an int. long lastDebounceTime = 0;  // the last time the output pin was toggled long debounceDelay = 50;    // the debounce time; increase if the output flickers // initialize the libr with the number of the intface pins double sensePinVthree = A0; double sensePinVfive = A1; double sensePinVfivesb = A2; double sensePinVtw = A3; double sensePinVrone = A4; double sensePinvrtwo = A5; //The current double sensePinIthree   = A6; double sensePinIfive   = A7; double sensePinIfivesb = A8; double sensePinItw  = A9; double sensePinIVrone = A10; double sensePinIVrtwo = A11; //setting up default or naming variables. double Voltsthree; double Voltsfive; double Voltsfivesb; double Voltstw; double VoltsVrone; double VoltsVrtwo; double Currentthree; double Currentfive; double Currentfivesb; double Currenttw; double CurrentVrone; double CurrentVrtwo; LiquidCrystal lcd(12, 11, 5, 4, 3, 2); LiquidCrystal lcd2(12, 10, 5, 4, 3, 2); //remove this if not working or glitchy void checkPowerOK(){   // when green is grounded   if (digitalRead(PWROK_PIN) == HIGH) {     lcd.setCursor(4, 1);     lcd.print("ON ");     lcd.setCursor(9, 3);     lcd.print("hello");   }   else if (digitalRead(PWROK_PIN) == LOW) {     lcd.setCursor(8,1);     lcd.print("OFF");   } } void togglePower(){ static unsigned long last_interrupt_time = 0; unsigned long interrupt_time = millis(); // If interrupts come faster than 200ms, assume it's a bounce and ignore if (interrupt_time - last_interrupt_time > 500) {    // set the power:   digitalWrite(PWRTRANS, PWRSTATE); //trans is pin 6 } PWRSTATE = !PWRSTATE; last_interrupt_time = interrupt_time;  } void setup() { analogReference (DEFAULT); pinMode(PWRBTN, INPUT); pinMode(PWRTRANS, OUTPUT); attachInterrupt(0, togglePower, RISING); digitalWrite(PWRTRANS, PWRSTATE);     lcd.begin(16, 4);   lcd2.begin(16, 2); // Print a message to the LCD. lcd.setCursor(0,0); //take this out if monitor buggy lcd.print("Bench PSU");// this code be fine lcd.setCursor(0,1); lcd.print("Monitor  V1.0"); lcd.setCursor(0,2); lcd.print("ICE"); lcd.setCursor(4,3); lcd.print("ROBOTICS"); lcd2.begin(16, 2); // replace with the date_time function lcd2.setCursor(0,0); lcd2.print("Hope 4 the best"); lcd2.setCursor(0, 1); lcd2.print("prep 4 the worst"); delay(3000); lcd.clear(); // wipes old message lcd.setCursor(5,0);  lcd.print("Building the Future"); lcd.setCursor(0,1); lcd.print("since   2014"); //Inset the time function somewhere in here lcd.clear(); lcd2.clear(); //lcd.createChar(0, blockChar);     Voltsthree=0; //setting my variables to Zero   Voltsfive=0;   Voltsfivesb=0;   Voltstw=0;   Currentthree=0; //Setting current to Zero on this Lcd   Currentfive=0;   Currentfivesb=0;   Currenttw=0;       VoltsVrone=0; // doing the same but for second lcd   VoltsVrtwo=0;     CurrentVrone=0;// same for current   CurrentVrtwo=0; } void loop () {checkPowerOK(); // check to see if power ok   Voltsthree = ((analogRead(sensePinVthree)) /218.0) *5; // or 7 aalso the 218.0 value will chaange to mine specific   if(Voltsthree <0){     Voltsthree=0;   }   Currentthree =(((analogRead(sensePinIthree)) / 212.0) -2.55) / 0.6666667;// why 0.667   if(Currentthree <0) {     Currentthree=0;   }   Voltsfive = ((analogRead(sensePinVfive)) /218.0) *5;   if(Voltsfive <0){     Voltsfive=0);   }   Currentfive =(((analogRead(sensePinIfive)) / 212.0) -2.55) / 0.6666667;// why 0.667   if(Currentfive <0) {     Currentfive=0;   }   Voltsfivesb =((analogRead(sensePinVfivesb)) /218.0) *5;   if(Voltsfivesb <0){     Voltsfivesb=0;   }   Currentfivesb =(((analogRead(sensePinIfivesb)) / 212.0) -2.55) / 0.6666667;// why 0.667   if(Currentfivesb <0) {     Currentfivesb=0;   }   Voltstw =((analogRead(sensePinVtw)) /218.0) *5;   if(Voltstw <0){     Voltstw= 0;   }   Currenttw =((analogRead(sensePinItw)) / 212.0) -2.55) / 0.6666667;// why 0.667   if(Currenttw <0){     Currenttw=0;   }     VoltsVrone =((analogRead(sensePinVrone)) /218.0) *5;   if(VoltsVrone <0){     VoltsVrone=0;   }   CurrentVrone =(((analogRead(sensePinIVrone)) / 212.0) -2.55) / 0.6666667;// why 0.667   if(CurrentVrone <0) {     CurrentVrone=0;   }     VoltsVrtwo =((analogRead(sensePinVrtwo)) /218.0) *5;   if(VoltsVrtwo <0){     VoltsVrtwo = 0;   }   CurrentVrtwo =(((analogRead(sensePinIVrtwo)) / 212.0) -2.55) / 0.6666667;// why 0.667   if(CurrentVrtwo <0) {     CurrentVrtwo=0;   }   //1st line   lcd.setCursor(0,0);   lcd.print("                "); //clear the line 1st line   lcd.setCursor(0,0);   lcd.print(Voltsthree);   lcd.setCursor(5,0):   lcd.print("V");   lcd.setCursor(7,0);   lcd.print(Currentthree);   lcd.setCursor(14,0);   lcd.print("A");     //2nd line   lcd.setCursor(0,1);                  // clear and print second line   lcd.print("                ");   lcd.setCursor(0,1);   lcd.print(Voltsfive);     lcd.setCursor(5,1);   lcd.print("V");   lcd.setCursor(7,1);   lcd.print(Currentfive);   lcd.setCursor(14,1);   lcd.print("A");     //3rd line   lcd.setCursor(0,2);           // clear line 3   lcd.print("                ");   lcd.setCursor(0,2);   lcd.print(Voltsfivesb);     lcd.setCursor(5,2);   lcd.print("V");   lcd.setCursor(7,2);   lcd.print(Currentfivesb);   lcd.setCursor(14,2);   lcd.print("A");     //4th line   lcd.setCursor(0,3);           // clear line 4   lcd.print("                ");   lcd.setCursor(0,3);   lcd.print(Voltstw);     lcd.setCursor(5,3);   lcd.print("V");   lcd.setCursor(7,3);   lcd.print(Currenttw);   lcd.setCursor(14,3);   lcd.print("A");     //1st line   lcd.setCursor(0,0);   lcd.print("                "); //clear the line 1st line   lcd.setCursor(0,0);   lcd.print(VoltsVrone.);   lcd.setCursor(5,0);   lcd.print("V");   lcd.setCursor(7,0);   lcd.print(CurrentVrone);   lcd.setCursor(14,0);   lcd.print("A");     //2nd line   lcd2.setCursor(0,1);                   // clear and print second line   lcd.print("                ");   lcd.setCursor(0,1);   lcd.print(VoltsVrtwo);     lcd.setCursor(5,1);   lcd.print("V");   lcd.setCursor(7,1);   lcd.print(CurrentVrtwo);   lcd.setCursor(14,1);   lcd.print("A");   }

Question by icey.hood   |  last reply


Problem in arduino code... you'll have to run this one to understand - Word Clock? Answered

I have been writing this code for the Word clock. I am trying to customize the code to fit into an atmega8, and use DS1307 RTC. Both of these is fine, but what is wrong is that when I upload my code and try to set the time by using the buttons, the time is not setting properly. I can increment minutes with the minutes button to 16, but not further. Hours works fine, but if, lets say the time is 6:36 on the arduino, then If I press the hour button, I find that time changes to 7:31. Five minutes less than what I expected. What am I overlooking here?  I advise to run the code and understand the problem. On the other hand Binary sketch size: 7164 bytes (of a 7168 byte maximum), this is just 4 bytes short of max. Can that be a part of the problem Code: #include // Display output pin assignments #define MTEN  Display1=Display1 | (1<<0)  #define HALF Display1=Display1 | (1<<1) #define QUARTER Display1=Display1 | (1<<2) #define TWENTY Display1=Display1 | (1<<3) #define MFIVE Display1=Display1 | (1<<4) #define MINUTES Display1=Display1 | (1<<5) #define PAST Display1=Display1 | (1<<6) #define UNUSED1 Display1=Display1 | (1<<7) #define TO Display2=Display2 | (1<<0) #define ONE Display2=Display2 | (1<<1) #define TWO Display2=Display2 | (1<<2) #define THREE Display2=Display2 | (1<<3) #define FOUR Display2=Display2 | (1<<4) #define HFIVE Display2=Display2 | (1<<5) #define SIX Display2=Display2 | (1<<6) #define UNUSED2 Display2=Display2 | (1<<7) #define SEVEN Display3=Display3 | (1<<0) #define EIGHT Display3=Display3 | (1<<1) #define NINE Display3=Display3 | (1<<2) #define HTEN Display3=Display3 | (1<<3) #define ELEVEN Display3=Display3 | (1<<4) #define TWELVE Display3=Display3 | (1<<5) #define OCLOCK  Display3=Display3 | (1<<6) #define UNUSED3 Display3=Display3 | (1<<7) #define DS1307_I2C_ADDRESS 0x68  // This is the I2C address #if defined(ARDUINO) && ARDUINO >= 100   // Arduino v1.0 and newer   #define I2C_WRITE Wire.write   #define I2C_READ Wire.read #else                                   // Arduino Prior to v1.0   #define I2C_WRITE Wire.send   #define I2C_READ Wire.receive #endif int  hr=12, mn=00, scnd=0; static unsigned long msTick =0;  // the number of Millisecond Ticks since we last                                  // incremented the second counter int  count; boolean selftestmode; boolean  DS1307Present=false;       // flag to indicate that the 1307 is there..    1 = present char Display1=0, Display2=0, Display3=0; // hardware constants static unsigned int LEDClockPin=5;    //11 d5 ok static unsigned int LEDDataPin=3;    //5 d3 static unsigned int LEDStrobePin=4;   //6 d4 static unsigned int MinuteButtonPin=6;  //d6 12 static unsigned int HourButtonPin=7;    //d7 13 static unsigned int PWMPin = 11; char buf[50]; // time output string for debugging byte decToBcd(byte b) {  return ( ((b/10) << 4) + (b%10) );} // Convert binary coded decimal to normal decimal numbers byte bcdToDec(byte b) {  return ( ((b >> 4)*10) + (b%16) );} void getTime() {   //read from chip and store in hr, mn, scnd   Wire.beginTransmission(DS1307_I2C_ADDRESS);   I2C_WRITE((uint8_t) 0x00);   Wire.endTransmission();     Wire.requestFrom(DS1307_I2C_ADDRESS, 3);   scnd = bcdToDec(I2C_READ());   mn =  bcdToDec(I2C_READ());   hr =  bcdToDec(I2C_READ()); } void setTime() {   //to be paranoid, we're going to first stop the clock   //to ensure we don't have rollovers while we're   //writing:   writeRTCreg(0,0x80);   //now, we'll write everything *except* the second   Wire.beginTransmission(DS1307_I2C_ADDRESS);   I2C_WRITE((uint8_t) 0x01);   I2C_WRITE(mn);   I2C_WRITE(hr);   Wire.endTransmission();   //now, we'll write the seconds; we didn't have to keep   //track of whether the clock was already running, because   //scnd already knows what we want it to be. This   //will restart the clock as it writes the new seconds value.   writeRTCreg(0,scnd); } byte readRTCreg(byte adr) {    if(adr > 0x3F) { return 0xff; }   Wire.beginTransmission(DS1307_I2C_ADDRESS);   I2C_WRITE(adr);   Wire.endTransmission();   Wire.requestFrom(DS1307_I2C_ADDRESS, 1);   return I2C_READ(); } void writeRTCreg(byte adr, byte val) { if(adr > 0x3F) { return; }    Wire.beginTransmission(DS1307_I2C_ADDRESS);    I2C_WRITE(adr);    I2C_WRITE(val);    Wire.endTransmission(); } void print_DS1307time() {   /* Format the time and date and insert into the temporary buffer */   snprintf(buf, sizeof(buf), "RTC time: %02d:%02d:%02d",   hr, mn, scnd);   /* Print the formatted string to serial so we can see the time */   Serial.println(buf); } void setup() {   // initialise the hardware   // initialize the appropriate pins as outputs:   pinMode(LEDClockPin, OUTPUT);   pinMode(LEDDataPin, OUTPUT);   pinMode(LEDStrobePin, OUTPUT);       //pinMode(BrightnessPin, INPUT);   pinMode(MinuteButtonPin, INPUT);   pinMode(HourButtonPin, INPUT);   digitalWrite(MinuteButtonPin, HIGH);  //set internal pullup   digitalWrite(HourButtonPin, HIGH); //set internal pullup   pinMode(PWMPin, OUTPUT);     Serial.begin(9600);   Wire.begin();    // test whether the DS1302 is there   Serial.print("Verifying DS1307 ");   // start by verifying that the chip has a valid signature   if (readRTCreg(0x20) == 0x55) {     // Signature is there - set the present flag and mmove on     DS1307Present=true;     Serial.println("Valid Signature");   }   else   {     // Signature isnt there - may be a new chip -     //   do a write to see if it will hold the signature     writeRTCreg(0x20,0x55);     if (readRTCreg(0x20) == 0x55) {       // We can store data - assume that it is a new chip that needs initialisation /*      // Start by clearing the clock halt flag.           //"Bit 7 of register 0 is the clock halt (CH) bit.           //When this bit is set to a 1, the oscillator is disabled."             byte _reg0_sec = decToBcd(scnd);             _reg0_sec = _reg0_sec & ~0x80;             writeRTCreg(0,_reg0_sec); */       // Set the time and date on the chip       scnd = 0;       mn = 0;       hr = 12;       setTime();       // set the DS1302 present flag       DS1307Present=true;       Serial.println("present - new chip initialised.");     }     else  Serial.println("absent");   }    msTick=millis();      // Initialise the msTick counter     selftest();   selftestmode=false;   if (DS1307Present) {     // Get the current time and date from the chip    getTime();     }     displaytime();        // display the current time } void ledsoff(void) { Display1=0; Display2=0; Display3=0; } void WriteLEDs(void) { // Now we write the actual values to the hardware shiftOut(LEDDataPin, LEDClockPin, MSBFIRST, Display3); shiftOut(LEDDataPin, LEDClockPin, MSBFIRST, Display2); shiftOut(LEDDataPin, LEDClockPin, MSBFIRST, Display1); digitalWrite(LEDStrobePin,HIGH); delay(2); digitalWrite(LEDStrobePin,LOW); } void selftest(void){   Serial.print("TEST");   analogWrite(PWMPin, 255);     ledsoff(); MTEN; WriteLEDs(); delay(500);   ledsoff(); HALF; WriteLEDs(); delay(500);   ledsoff(); QUARTER; WriteLEDs(); delay(500);   ledsoff(); TWENTY; WriteLEDs(); delay(500);   ledsoff(); MFIVE; WriteLEDs(); delay(500);   ledsoff(); MINUTES; WriteLEDs(); delay(500);   ledsoff(); PAST; WriteLEDs(); delay(500);   ledsoff(); TO; WriteLEDs(); delay(500);   ledsoff(); ONE; WriteLEDs(); delay(500);   ledsoff(); TWO; WriteLEDs(); delay(500);   ledsoff(); THREE; WriteLEDs(); delay(500);   ledsoff(); FOUR; WriteLEDs(); delay(500);   ledsoff(); HFIVE; WriteLEDs(); delay(500);   ledsoff(); SIX; WriteLEDs(); delay(500);   ledsoff(); SEVEN; WriteLEDs(); delay(500);   ledsoff(); EIGHT; WriteLEDs(); delay(500);   ledsoff(); NINE; WriteLEDs(); delay(500);   ledsoff(); HTEN; WriteLEDs(); delay(500);   ledsoff(); ELEVEN; WriteLEDs(); delay(500);   ledsoff(); TWELVE; WriteLEDs(); delay(500);   ledsoff(); OCLOCK; WriteLEDs(); delay(500); } void displaytime(void){   // start by clearing the display to a known state   ledsoff();     Serial.print("It is ");   // now we display the appropriate minute counter   if ((mn>4) && (mn<10)) {     MFIVE;     MINUTES;     Serial.print("Five Minutes ");   }   if ((mn>9) && (mn<15)) {     MTEN;     MINUTES;     Serial.print("Ten Minutes ");   }   if ((mn>14) && (mn<20)) {     QUARTER;       Serial.print("Quarter ");   }   if ((mn>19) && (mn<25)) {     TWENTY;     MINUTES;     Serial.print("Twenty Minutes ");   }   if ((mn>24) && (mn<30)) {     TWENTY;     MFIVE;     MINUTES;     Serial.print("Twenty Five Minutes ");   }    if ((mn>29) && (mn<35)) {     HALF;     Serial.print("Half ");   }   if ((mn>34) && (mn<40)) {     TWENTY;     MFIVE;     MINUTES;     Serial.print("Twenty Five Minutes ");   }    if ((mn>39) && (mn<45)) {     TWENTY;     MINUTES;     Serial.print("Twenty Minutes ");   }   if ((mn>44) && (mn<50)) {     QUARTER;     Serial.print("Quarter ");   }   if ((mn>49) && (mn<55)) {     MTEN;     MINUTES;     Serial.print("Ten Minutes ");   }   if (mn>54) {     MFIVE;     MINUTES;     Serial.print("Five Minutes ");   }   if ((mn <5))   {     switch (hr) {     case 1:       ONE;       Serial.print("One ");       break;     case 2:       TWO;       Serial.print("Two ");       break;     case 3:       THREE;       Serial.print("Three ");       break;     case 4:       FOUR;       Serial.print("Four ");       break;     case 5:       HFIVE;       Serial.print("Five ");       break;     case 6:       SIX;       Serial.print("Six ");       break;     case 7:       SEVEN;       Serial.print("Seven ");       break;     case 8:       EIGHT;       Serial.print("Eight ");       break;     case 9:       NINE;       Serial.print("Nine ");       break;     case 10:       HTEN;       Serial.print("Ten ");       break;     case 11:       ELEVEN;       Serial.print("Eleven ");       break;     case 12:       TWELVE;       Serial.print("Twelve ");       break;     }   OCLOCK;   Serial.println("O'Clock");   }   else     if ((mn < 35) && (mn >4))     {       PAST;       Serial.print("Past ");       switch (hr) {     case 1:       ONE;       Serial.println("One ");       break;     case 2:       TWO;       Serial.println("Two ");       break;     case 3:       THREE;       Serial.println("Three ");       break;     case 4:       FOUR;       Serial.println("Four ");       break;     case 5:       HFIVE;       Serial.println("Five ");       break;     case 6:       SIX;       Serial.println("Six ");       break;     case 7:       SEVEN;       Serial.println("Seven ");       break;     case 8:       EIGHT;       Serial.println("Eight ");       break;     case 9:       NINE;       Serial.println("Nine ");       break;     case 10:       HTEN;       Serial.println("Ten ");       break;     case 11:       ELEVEN;       Serial.println("Eleven ");       break;     case 12:       TWELVE;       Serial.println("Twelve ");       break;       }     }     else     {       // if we are greater than 34 minutes past the hour then display       // the next hour, as we will be displaying a 'to' sign       TO;       Serial.print("To ");       switch (hr) {       case 1:         TWO;        Serial.println("Two ");        break;       case 2:         THREE;       Serial.println("Three ");         break;       case 3:         FOUR;       Serial.println("Four ");         break;       case 4:         HFIVE;       Serial.println("Five ");         break;       case 5:         SIX;       Serial.println("Six ");         break;       case 6:         SEVEN;       Serial.println("Seven ");         break;       case 7:         EIGHT;       Serial.println("Eight ");         break;       case 8:         NINE;       Serial.println("Nine ");         break;       case 9:         HTEN;       Serial.println("Ten ");         break;       case 10:         ELEVEN;       Serial.println("Eleven ");         break;       case 11:         TWELVE;       Serial.println("Twelve ");         break;       case 12:         ONE;       Serial.println("One ");         break;       }     }    WriteLEDs();    } void incrementtime(void){   // increment the time counters keeping care to rollover as required   scnd=0;   if (++mn >= 60) {     mn=0;     if (++hr == 13) {       hr=1;      }   }    // debug outputs   Serial.println(); //  if (DS1307Present) //  print_DS1307time(); //  else{ //  Serial.print("Arduino Time: " );   Serial.print(hr);   Serial.print(":");   Serial.print(mn);   Serial.print(":");   Serial.println(scnd); //  } } void loop(void) {     //selftest(); int aread = sq(analogRead(3)/4)+3;   //Uncomment the following line and comment the next one in order to   //  enable dimming via a potentiometer connected to pin 0:   analogWrite(PWMPin, aread>255 ? 255:aread);   //analogWrite(PWMPin, 255);       // heart of the timer - keep looking at the millisecond timer on the Arduino     // and increment the seconds counter every 1000 ms     if ( millis() - msTick >999) {         msTick=millis();         scnd++; /*        // Flash the onboard Pin13 Led so we know something is hapening!         digitalWrite(13,HIGH);         delay(100);         digitalWrite(13,LOW);    */    }                 //test to see if we need to increment the time counters     if (scnd==60)     {       incrementtime();       displaytime();     } if (DS1307Present) {     // Get the current time and date from the chip      getTime();     }     // test to see if a forward button is being held down     // for time setting     if ( (digitalRead(MinuteButtonPin) ==0 ) && scnd!=1)       // the forward button is down       // and it has been more than one second since we       // last looked     {       mn=(((mn/5)*5) +5);       scnd=0;       incrementtime();       scnd++;  // Increment the second counter to ensure that the name       // flash doesnt happen when setting time       if (DS1307Present) {       // Set the time on the chip       setTime();     }     delay(100);       displaytime();     }     // test to see if the back button is being held down     // for time setting     if ((digitalRead(HourButtonPin)==0 ) && scnd!=1)     {       /*       minute=(((minute/5)*5) -5);       second=0; // decrement the minute counter       if (minute<0) {         minute=55;         if (--hour <0) hour=12;       }       */             mn = (mn/5)*5;  //round minute down to previous 5 min interval       if (++hr == 13) {         hr=1;        }       incrementtime();       scnd++;  // Increment the second counter to ensure that the name       // flash doesnt happen when setting time        if (DS1307Present) {       // Set the time and date on the chip       setTime();     }     delay(100);       displaytime();     } }

Question by pro2xy   |  last reply


: Arduino + Adafruit wave sheild + IR + Keypad sound board

Hi , was wondering if you could point me in the right direction I'm very new to Arduino I built last year a simple board with adafruit wave shield and added a simple 12 digit key pad to play 12 sounds + power up I have got the codes for the KEYES IR receiver so know the IR is correctly connected and library loaded im trying to integrate the IR code so can change the sounds by IR remote ideally with option of the buttons (if have to loose the buttons and just use remote that's fine) have copied the code below for how it works now just buttons   I found some code for Cylon Pumpkin that works great with just the remote but would also like to integrate the 12 digit keypad Thank you in advance for any help or pointers you can suggest Richard CODE FOR 12 DIGIT BUTTON PRESS /* ADAVOICE is an Arduino-based voice pitch changer plus WAV playback. Fun for Halloween costumes, comic convention getups and other shenanigans! Hardware requirements: - Arduino Uno, Duemilanove or Diecimila (not Mega or Leonardo compatible). - Adafruit Wave Shield - Speaker attached to Wave Shield output - Battery for portable use If using the voice pitch changer, you will also need: - Adafruit Microphone Breakout - 10K potentiometer for setting pitch (or hardcode in sketch) If using the WAV playback, you will also need: - SD card - Keypad, buttons or other sensor(s) for triggering sounds Software requirements: - WaveHC library for Arduino - Demo WAV files on FAT-formatted SD card This example sketch uses a 3x4 keypad for triggering sounds...but with some changes could be adapted to use several discrete buttons, Hall effect sensors, force-sensing resistors (FSRs), I2C keypads, etc. (or if you just want the voice effect, no buttons at all). Connections: - 3.3V to mic amp+, 1 leg of potentiometer and Arduino AREF pin - GND to mic amp-, opposite leg of potentiometer - Analog pin 0 to mic amp output - Analog pin 1 to center tap of potentiometer - Wave Shield output to speaker or amplifier - Matrix is wired to pins A2, A3, A4, A5 (rows) and 6, 7, 8 (columns) - Wave shield is assumed wired as in product tutorial Potentiometer sets playback pitch. Pitch adjustment does NOT work in realtime -- audio sampling requires 100% of the ADC. Pitch setting is read at startup (or reset) and after a WAV finishes playing. POINT SPEAKER AWAY FROM MIC to avoid feedback. Written by Adafruit industries, with portions adapted from the 'PiSpeakHC' sketch included with WaveHC library. */ #include #include SdReader card; // This object holds the information for the card FatVolume vol; // This holds the information for the partition on the card FatReader root; // This holds the information for the volumes root directory FatReader file; // This object represent the WAV file for a pi digit or period WaveHC wave; // This is the only wave (audio) object, -- we only play one at a time #define error(msg) error_P(PSTR(msg)) // Macro allows error messages in flash memory #define ADC_CHANNEL 0 // Microphone on Analog pin 0 // Wave shield DAC: digital pins 2, 3, 4, 5 #define DAC_CS_PORT PORTD #define DAC_CS PORTD2 #define DAC_CLK_PORT PORTD #define DAC_CLK PORTD3 #define DAC_DI_PORT PORTD #define DAC_DI PORTD4 #define DAC_LATCH_PORT PORTD #define DAC_LATCH PORTD5 uint16_t in = 0, out = 0, xf = 0, nSamples; // Audio sample counters uint8_t adc_save; // Default ADC mode // WaveHC didn't declare it's working buffers private or static, // so we can be sneaky and borrow the same RAM for audio sampling! extern uint8_t buffer1[PLAYBUFFLEN], // Audio sample LSB buffer2[PLAYBUFFLEN]; // Audio sample MSB #define XFADE 16 // Number of samples for cross-fade #define MAX_SAMPLES (PLAYBUFFLEN - XFADE) // Remaining available audio samples // Keypad information: uint8_t rows[] = { A2, A3, A4, A5 }, // Keypad rows connect to these pins cols[] = { 6, 7, 8, 9 }, // Keypad columns connect to these pins r = 0, // Current row being examined prev = 255, // Previous key reading (or 255 if none) count = 0; // Counter for button debouncing #define DEBOUNCE 10 // Number of iterations before button 'takes' // Keypad/WAV information. Number of elements here should match the // number of keypad rows times the number of columns, plus one: const char *sound[] = { "Crashing" , "Damaged", "InFlight" , "PowerUp" , // Row 1 = Darth Vader sounds "Brkdown3" , "Brkdown2" , "Brkdown" , "PowerUp" , // Row 2 = Godzilla sounds "Landing", "drain" , "Shutdown" , "PowerUp" , // Row 3 = Dug the dog sounds "Silent", "TakeOff", "Vortex" , "PowerUp" , // Row 4 = Cartoon/SFX sound "PowerUp" }; // Extra item = boot sound //////////////////////////////////// SETUP void setup() { uint8_t i; Serial.begin(9600); // The WaveHC library normally initializes the DAC pins...but only after // an SD card is detected and a valid file is passed. Need to init the // pins manually here so that voice FX works even without a card. pinMode(2, OUTPUT); // Chip select pinMode(3, OUTPUT); // Serial clock pinMode(4, OUTPUT); // Serial data pinMode(5, OUTPUT); // Latch digitalWrite(2, HIGH); // Set chip select high // Init SD library, show root directory. Note that errors are displayed // but NOT regarded as fatal -- the program will continue with voice FX! if(!card.init()) SerialPrint_P("Card init. failed!"); else if(!vol.init(card)) SerialPrint_P("No partition!"); else if(!root.openRoot(vol)) SerialPrint_P("Couldn't open dir"); else { PgmPrintln("Files found:"); root.ls(); // Play startup sound (last file in array). playfile(sizeof(sound) / sizeof(sound[0]) - 1); } // Optional, but may make sampling and playback a little smoother: // Disable Timer0 interrupt. This means delay(), millis() etc. won't // work. Comment this out if you really, really need those functions. TIMSK0 = 0; // Set up Analog-to-Digital converter: analogReference(EXTERNAL); // 3.3V to AREF adc_save = ADCSRA; // Save ADC setting for restore later // Set keypad rows to outputs, set to HIGH logic level: for(i=0; i pinMode(rows[i], OUTPUT); digitalWrite(rows[i], HIGH); } // Set keypad columns to inputs, enable pull-up resistors: for(i=0; i pinMode(cols[i], INPUT); digitalWrite(cols[i], HIGH); } while(wave.isplaying); // Wait for startup sound to finish... startPitchShift(); // and start the pitch-shift mode by default. } //////////////////////////////////// LOOP // As written here, the loop function scans a keypad to triggers sounds // (stopping and restarting the voice effect as needed). If all you need // is a couple of buttons, it may be easier to tear this out and start // over with some simple digitalRead() calls. void loop() { uint8_t c, button; // Set current row to LOW logic state... digitalWrite(rows[r], LOW); // ...then examine column buttons for a match... for(c=0; c if(digitalRead(cols[c]) == LOW) { // First match. button = r * sizeof(cols) + c; // Get button index. if(button == prev) { // Same button as before? if(++count >= DEBOUNCE) { // Yes. Held beyond debounce threshold? if(wave.isplaying) wave.stop(); // Stop current WAV (if any) else stopPitchShift(); // or stop voice effect playfile(button); // and play new sound. while(digitalRead(cols[c]) == LOW); // Wait for button release. prev = 255; // Reset debounce values. count = 0; } } else { // Not same button as prior pass. prev = button; // Record new button and count = 0; // restart debounce counter. } } } // Restore current row to HIGH logic state and advance row counter... digitalWrite(rows[r], HIGH); if(++r >= sizeof(rows)) { // If last row scanned... r = 0; // Reset row counter // If no new sounds have been triggered at this point, and if the // pitch-shifter is not running, re-start it... if(!wave.isplaying && !(TIMSK2 & _BV(TOIE2))) startPitchShift(); } } //////////////////////////////////// HELPERS // Open and start playing a WAV file void playfile(int idx) { char filename[13]; (void)sprintf(filename,"%s.wav", sound[idx]); Serial.print("File: "); Serial.println(filename); if(!file.open(root, filename)) { PgmPrint("Couldn't open file "); Serial.print(filename); return; } if(!wave.create(file)) { PgmPrintln("Not a valid WAV"); return; } wave.play(); } //////////////////////////////////// PITCH-SHIFT CODE void startPitchShift() { // Read analog pitch setting before starting audio sampling: int pitch = analogRead(1); Serial.print("Pitch: "); Serial.println(pitch); // Right now the sketch just uses a fixed sound buffer length of // 128 samples. It may be the case that the buffer length should // vary with pitch for better results...further experimentation // is required here. nSamples = 128; //nSamples = F_CPU / 3200 / OCR2A; // ??? //if(nSamples > MAX_SAMPLES) nSamples = MAX_SAMPLES; //else if(nSamples < (XFADE * 2)) nSamples = XFADE * 2; memset(buffer1, 0, nSamples + XFADE); // Clear sample buffers memset(buffer2, 2, nSamples + XFADE); // (set all samples to 512) // WaveHC library already defines a Timer1 interrupt handler. Since we // want to use the stock library and not require a special fork, Timer2 // is used for a sample-playing interrupt here. As it's only an 8-bit // timer, a sizeable prescaler is used (32:1) to generate intervals // spanning the desired range (~4.8 KHz to ~19 KHz, or +/- 1 octave // from the sampling frequency). This does limit the available number // of speed 'steps' in between (about 79 total), but seems enough. TCCR2A = _BV(WGM21) | _BV(WGM20); // Mode 7 (fast PWM), OC2 disconnected TCCR2B = _BV(WGM22) | _BV(CS21) | _BV(CS20); // 32:1 prescale OCR2A = map(pitch, 0, 1023, F_CPU / 32 / (9615 / 2), // Lowest pitch = -1 octave F_CPU / 32 / (9615 * 2)); // Highest pitch = +1 octave // Start up ADC in free-run mode for audio sampling: DIDR0 |= _BV(ADC0D); // Disable digital input buffer on ADC0 ADMUX = ADC_CHANNEL; // Channel sel, right-adj, AREF to 3.3V regulator ADCSRB = 0; // Free-run mode ADCSRA = _BV(ADEN) | // Enable ADC _BV(ADSC) | // Start conversions _BV(ADATE) | // Auto-trigger enable _BV(ADIE) | // Interrupt enable _BV(ADPS2) | // 128:1 prescale... _BV(ADPS1) | // ...yields 125 KHz ADC clock... _BV(ADPS0); // ...13 cycles/conversion = ~9615 Hz TIMSK2 |= _BV(TOIE2); // Enable Timer2 overflow interrupt sei(); // Enable interrupts } void stopPitchShift() { ADCSRA = adc_save; // Disable ADC interrupt and allow normal use TIMSK2 = 0; // Disable Timer2 Interrupt } ISR(ADC_vect, ISR_BLOCK) { // ADC conversion complete // Save old sample from 'in' position to xfade buffer: buffer1[nSamples + xf] = buffer1[in]; buffer2[nSamples + xf] = buffer2[in]; if(++xf >= XFADE) xf = 0; // Store new value in sample buffers: buffer1[in] = ADCL; // MUST read ADCL first! buffer2[in] = ADCH; if(++in >= nSamples) in = 0; } ISR(TIMER2_OVF_vect) { // Playback interrupt uint16_t s; uint8_t w, inv, hi, lo, bit; int o2, i2, pos; // Cross fade around circular buffer 'seam'. if((o2 = (int)out) == (i2 = (int)in)) { // Sample positions coincide. Use cross-fade buffer data directly. pos = nSamples + xf; hi = (buffer2[pos] << 2) | (buffer1[pos] >> 6); // Expand 10-bit data lo = (buffer1[pos] << 2) | buffer2[pos]; // to 12 bits } if((o2 < i2) && (o2 > (i2 - XFADE))) { // Output sample is close to end of input samples. Cross-fade to // avoid click. The shift operations here assume that XFADE is 16; // will need adjustment if that changes. w = in - out; // Weight of sample (1-n) inv = XFADE - w; // Weight of xfade pos = nSamples + ((inv + xf) % XFADE); s = ((buffer2[out] << 8) | buffer1[out]) * w + ((buffer2[pos] << 8) | buffer1[pos]) * inv; hi = s >> 10; // Shift 14 bit result lo = s >> 2; // down to 12 bits } else if (o2 > (i2 + nSamples - XFADE)) { // More cross-fade condition w = in + nSamples - out; inv = XFADE - w; pos = nSamples + ((inv + xf) % XFADE); s = ((buffer2[out] << 8) | buffer1[out]) * w + ((buffer2[pos] << 8) | buffer1[pos]) * inv; hi = s >> 10; // Shift 14 bit result lo = s >> 2; // down to 12 bits } else { // Input and output counters don't coincide -- just use sample directly. hi = (buffer2[out] << 2) | (buffer1[out] >> 6); // Expand 10-bit data lo = (buffer1[out] << 2) | buffer2[out]; // to 12 bits } // Might be possible to tweak 'hi' and 'lo' at this point to achieve // different voice modulations -- robot effect, etc.? DAC_CS_PORT &= ~_BV(DAC_CS); // Select DAC // Clock out 4 bits DAC config (not in loop because it's constant) DAC_DI_PORT &= ~_BV(DAC_DI); // 0 = Select DAC A, unbuffered DAC_CLK_PORT |= _BV(DAC_CLK); DAC_CLK_PORT &= ~_BV(DAC_CLK); DAC_CLK_PORT |= _BV(DAC_CLK); DAC_CLK_PORT &= ~_BV(DAC_CLK); DAC_DI_PORT |= _BV(DAC_DI); // 1X gain, enable = 1 DAC_CLK_PORT |= _BV(DAC_CLK); DAC_CLK_PORT &= ~_BV(DAC_CLK); DAC_CLK_PORT |= _BV(DAC_CLK); DAC_CLK_PORT &= ~_BV(DAC_CLK); for(bit=0x08; bit; bit>>=1) { // Clock out first 4 bits of data if(hi & bit) DAC_DI_PORT |= _BV(DAC_DI); else DAC_DI_PORT &= ~_BV(DAC_DI); DAC_CLK_PORT |= _BV(DAC_CLK); DAC_CLK_PORT &= ~_BV(DAC_CLK); } for(bit=0x80; bit; bit>>=1) { // Clock out last 8 bits of data if(lo & bit) DAC_DI_PORT |= _BV(DAC_DI); else DAC_DI_PORT &= ~_BV(DAC_DI); DAC_CLK_PORT |= _BV(DAC_CLK); DAC_CLK_PORT &= ~_BV(DAC_CLK); } DAC_CS_PORT |= _BV(DAC_CS); // Unselect DAC if(++out >= nSamples) out = 0; } CODE I FOUND FOR IR  ClyonPumpkin That I want to integrate in above   /* * Text-to-speech example to speak the first n digits of pi. * The number is stored in flash, each digit is spoken one at a time. */ #include #include #include SdReader card;    // This object holds the information for the card FatVolume vol;    // This holds the information for the partition on the card FatReader root;   // This holds the information for the volumes root directory FatReader file;   // This object represent the WAV file for a pi digit or period WaveHC wave;      // This is the only wave (audio) object, since we will only play one at a time char eyesound[13]="eye2.wav"; int mute = 0; /* * Define macro to put error messages in flash memory */ #define error(msg) error_P(PSTR(msg)) // IR Remote code int RECV_PIN = 9;  // pin 11 used by SD card interface so select pin 9 for IR IRrecv irrecv(RECV_PIN); decode_results results; long lasttime=0, lastcode=0, timediff=0; //////////////////////////////////// SETUP void setup() {   // set up Serial library at 9600 bps   Serial.begin(9600);               if (!card.init()) {     error("Card init. failed!");   }   if (!vol.init(card)) {     error("No partition!");   }   if (!root.openRoot(vol)) {     error("Couldn't open dir");   }   irrecv.enableIRIn(); // Start the IR receiver } /////////////////////////////////// LOOP void loop() {   if(mute == 0) playcomplete(eyesound);   // check for keypress happened   if (irrecv.decode(&results;)) {      Serial.println(results.value, HEX);      switch (results.value) {        case 0x83228B74:    // 1          playcomplete("command.wav");          break;        case 0x83228F70:    // 2          playcomplete("entertan.wav");          break;        case 0x8322906F:    // 3          playcomplete("extermin.wav");          break;        case 0x83228A75:    // 4          playcomplete("leader.wav");          break;        case 0x8322847B:    // 5          playcomplete("survivor.wav");          break;         case 0x83227887:    // 6          playcomplete("atention.wav");          break;        case 0x8322629D:    // vol up          mute = 0;         // mute off          break;         case 0x83226E91:    // mute          { Serial.println("mute detected");            timediff=millis()-lasttime;            Serial.println(timediff);            if(lastcode!=results.value || (lastcode==results.value && (timediff>1600)) ) {               if( mute == 0 ) { // is mute off?                  Serial.println("toggle off to on");                  mute = 1;      // turn on                  // delay(1000);    // wait a bit for debounce                  break;                 }               if( mute == 1 ) { // is mute on?                  mute = 0;      // turn off                  Serial.println("toggle on to off");                  break;                 }              } // end if             break;           } // end case        } // end switch      lastcode = results.value;      lasttime = millis();      irrecv.resume();   // Receive the next value   } } /////////////////////////////////// HELPERS /* * print error message and halt */ void error_P(const char *str) {   PgmPrint("Error: ");   SerialPrint_P(str);   sdErrorCheck();   while(1); } /* * print error message and halt if SD I/O error */ void sdErrorCheck(void) {   if (!card.errorCode()) return;   PgmPrint("\r\nSD I/O error: ");   Serial.print(card.errorCode(), HEX);   PgmPrint(", ");   Serial.println(card.errorData(), HEX);   while(1); } /* * Play a file and wait for it to complete */ void playcomplete(char *name) {   playfile(name);   while (wave.isplaying);     // see if an error occurred while playing   sdErrorCheck(); } /* * Open and start playing a WAV file */ void playfile(char *name) {   if (wave.isplaying) {// already playing something, so stop it!     wave.stop(); // stop it   }   if (!file.open(root, name)) {     PgmPrintln("Couldn't open file ");     Serial.print(name);     return;   }   if (!wave.create(file)) {     PgmPrintln("Not a valid WAV");     return;   }   // ok time to play!   wave.play(); }

Topic by SithLordIII