texts: Can I increase the 10 event limit in Simon Monk's Timer library?

texts:
On Dr. Monk's library page here, he states: "You can attach up to 10 events to a timer." I am wondering if this is a hardware limit, or if it was an arbitrary number he chose for his library.

In Timer.h, he defines the maximum number of timed events like this:

#define MAX_NUMBER_OF_EVENTS (10)

Can you foresee any problems if I changed that to a higher number? My sketch is already approaching the limit of 10 timed events running at the same time, so it would help me if I was able to increase the maximum number of timed events to about 20.


texts:
I'm trying to understand how to fully use the COMPB vector ISR of Timer0 on the ATMega328 (standard Arduino core). I realize it will make delay() and millis() not work but that's ok by me. I've setup some test code that should output a 244Hz signal on D4 and 488Hz on D5 (note, this is running at 8MHz). But D5 (COMPB) is always what D4 (COMPA) is. Any thoughts? Code below:

#include <avr/interrupt.h>

volatile bool stateA = false;
ISR(TIMER0_COMPA_vect)
{
    if (stateA)
        PORTD |= _BV(PIND4);
    else
        PORTD &= ~(_BV(PIND4));

    stateA = !stateA;
}

volatile bool stateB = false;
ISR(TIMER0_COMPB_vect)
{
    if (stateB)
        PORTD |= _BV(PIND5);
    else
        PORTD &= ~(_BV(PIND5));

    stateB = !stateB;
}

void setup()
{
    DDRD |= _BV(PIND4) | _BV(PIND5);

    //set timer0 interrupt at 2kHz
    TCCR0A = 0;// set entire TCCR2A register to 0
    TCCR0B = 0;// same for TCCR2B
    TCNT0 = 0;//initialize counter value to 0
    // set compare match register for 2khz increments
    OCR0A = 255;//244Hz
    OCR0B = 127;//488Hz
    // turn on CTC mode
    TCCR0A |= (1 << WGM01);
    // Set CS01 and CS00 bits for 64 prescaler
    TCCR0B |= (1 << CS01) | (1 << CS00);
    // enable timer compare interrupt
    TIMSK0 |= (1 << OCIE0B) | (1 << OCIE0A);

    interrupts();

}

Update: After thinking about it, I'm realizing that it's not that I need two separate frequencies (though I just kinda wanted to know how, so this is good stuff) but I just need two separate interrupts, only using Timer0 (1 & 2 are already in use elsewhere). They can be the same frequency, most likely. I probably could put all the functionality I need in the same TIMER0_COMPA_vect, however I was trying to use that in a library I was writing and was trying to keep the functionality separate... this may not be possible.


texts: AC meter By ADC timer interrupt from Nick Gammon

texts:
I want to read ADC from the pin A0 and A1. I have written in this code, however.

I took this code came from Nick Gammon

Thank You
//////////////////////////////////////////////////////////////////////////////

this is code

const byte adcPin = 0;  // A0

const int MAX_RESULTS = 256;

volatile int results [MAX_RESULTS];
volatile int resultNumber;

// ADC complete ISR
ISR (ADC_vect)
  {
  if (resultNumber >= MAX_RESULTS)
    ADCSRA = 0;  // turn off ADC
  else
    results [resultNumber++] = ADC;
  }  // end of ADC_vect

EMPTY_INTERRUPT (TIMER1_COMPB_vect);

void setup ()
  {
  Serial.begin (115200);
  Serial.println ();

  // reset Timer 1
  TCCR1A = 0;
  TCCR1B = 0;
  TCNT1 = 0;
  TCCR1B = bit (CS11) | bit (WGM12);  // CTC, prescaler of 8
  TIMSK1 = bit (OCIE1B);  // WTF?
  OCR1A = 39;
  OCR1B = 39;   // 20 uS - sampling frequency 50 kHz

  ADCSRA =  bit (ADEN) | bit (ADIE) | bit (ADIF);   // turn ADC on, want interrupt on completion
  ADCSRA |= bit (ADPS2);  // Prescaler of 16
  ADMUX = bit (REFS0) | (adcPin & 7);
  ADCSRB = bit (ADTS0) | bit (ADTS2);  // Timer/Counter1 Compare Match B
  ADCSRA |= bit (ADATE);   // turn on automatic triggering

  // wait for buffer to fill
  while (resultNumber < MAX_RESULTS)
    { }

  for (int i = 0; i < MAX_RESULTS; i++)
    Serial.println (results [i]);

  }  // end of setup

void loop () { }


texts: Sorry folks, I understand this question has been asked quite few times, but I wasn't able to find a definitive answer: my Mega 2560 R3 is powered by 7.7V from Vin, and runs at a steady 135mA (in theory it's 2.7 x 0.135 = 0.38W dissipation). But the regulator with a heat sink still gets hot. Not burning hot but definitely to a point where you'd question whether it's a good idea to leave it running for months.Is this normal? Also is this a sustainable plan for a long running project?The 7.7V (7.7 because I remember the regulator needs a voltage around that to work) is coming from a variable step down module that could deliver a 5V. However I've noticed although it does stabilize at 5V , when the power just comes on it would surge to ~9V for a fraction of a second. My understanding is the 5V input on arduino is assuming clean 5V, so I hesitated there. Any suggestions? Thanks!


texts: Program to run two motors with Motor driver

texts:
I'm trying to make a program that would run two motors clockwise and then anticlockwise. But my program is causing my motors to only run clockwise everytime . It doesn't run anticlockwise at all. Can anyone help me find the bug?

Main code:

void loop()
{
  // turn on motor A
  digitalWrite(In1, HIGH);
  digitalWrite(In2, LOW);
  // set speed to 150 out 255
  analogWrite(EnA, 150);
  // turn on motor B
  digitalWrite(In3, HIGH);
  digitalWrite(In4, LOW);
  // set speed to 150 out 255
  analogWrite(EnB, 150);
  delay(2000);
   digitalWrite(In1, LOW);
  digitalWrite(In2, HIGH);
   digitalWrite(In3,LOW);
  digitalWrite(In4, HIGH);
  // now turn off motors
  digitalWrite(In1, LOW);
  digitalWrite(In2, LOW);
  digitalWrite(In3, LOW);
  digitalWrite(In4, LOW);
  delay(2000);
}


texts: Im building a bedside alarm clock/home assistant. I have a few buttons that input, an LCD display and some RGB LEDs. The LCD and RGBs are only on when commanded to be on. I was wondering if I could leave the mega plugged in and constantly running or if that would burn it out. Im a bit new to this so sorry if this is dumb. If it would burn out, how long is its lifetime?


texts: Execute Code While Refreshing a 7 Segment LED Display

texts:
I'm using the following library to drive a 4 digit, 7 segment LED display:

http://playground.arduino.cc/Main/SevenSegmentLibrary

The display is showing the temperature which it gets from a DS18B20 temperature sensor.  Since the LED display constantly needs to be refreshed, when the code runs to get the current temperature, the display temporarily turns off because the LEDs are not being refreshed.  The code I am using is below. Is there anyway to prevent the LED display from turning off while the temperature request code runs?

#include <SevSeg.h>
#include <OneWire.h>
#include <DallasTemperature.h>

SevSeg sevseg;

unsigned long timer; // the timer
unsigned long INTERVAL = 30000; // the repeat interval (30 seconds)

#define ONE_WIRE_BUS 2
OneWire oneWire(ONE_WIRE_BUS);
DallasTemperature sensors(&oneWire);

void setup() {
  byte numDigits = 4;
  byte digitPins[] = {A2, A3, A4, A5};
  byte segmentPins[] = {8, 10, 6, 4, 3, 9, 7, 5};

  sevseg.begin(COMMON_CATHODE, numDigits, digitPins, segmentPins);
  sevseg.setBrightness(90);

  // Get the initial temperature and show it on the LED display
  sensors.begin();
  sensors.requestTemperatures();
  sevseg.setNumber(sensors.getTempCByIndex(0), 1);
  timer = millis(); // start timer
}

void loop() {
  if ((millis()-timer) > INTERVAL) {
    // Reset the timer and get/display the current temperature
    timer += INTERVAL;
    sensors.requestTemperatures();
    sevseg.setNumber(sensors.getTempCByIndex(0), 1);
  }

  sevseg.refreshDisplay(); // Must run repeatedly to refresh the LED display
}


texts: How to wire a hall effect sensor to arduino?

texts:
it's a UGN3503 hall effect sensor, in some schematics they used a 100uf capacitors and data connected to analog pin and in some a pull up resistor and data connected to digital pin.

as someone new to both electronics and arduino i'm a bit confused on how to wire the sensor to the arduino.

what i want is just simply read the data from sensor and if the number is above or under defined value do something.

do i need a pull up resistor and/or capacitor?

what's the right and standard way to wire a UGN3503 to arduino?


texts: Unexpected accident of my board, CH341 issue for Linux or Dead ESP?

texts:
I have early midnight accident of my Lolin/Wemos boards. I tried uploads my sketch with a assembly VIN to GND as my reset button, when i uploads my sketch at more one hundred times, i get my boards cannot be online again or my port cannot readable to my Ubuntu as /dev/ttyXXX. usually when i plugged the Usb3.0 cable, the blink led should be turn on at my boards but i didn't get it. How  i can re-flash my boards to be online again?

Thanks in advance.


texts:
Problem
I'm stuck on triggering different switch. I'll explain what each of  my switch should do. Output of this setup : No output from relayPin
mainPin

Main power of the switch to control relayPin — keeps on/off
Override reedPin state
Let SecondState

reedPin

Secondary power switch to control relayPin — depends on mainPin on/off state
Overridden by mainPin
Let FirstState

*another explanation in comment
Is it caused by coding or hardware? Pardon my ignorance, it is my beginner code. I would appreciate any help, thank you.
Code
const int reedPin = 8; // Reed Switch
const int mainPin = 9; // Main Switch
const int relayPin = 6; // Relay

int FirstState = 0;
int SecondState = 0;

void setup() {
    pinMode(relayPin, OUTPUT);
    pinMode(reedPin, INPUT);
    pinMode(mainPin, INPUT);

}

void loop() {
    FirstState = digitalRead(reedPin);
    SecondState = digitalRead(mainPin);
    if (FirstState == HIGH) {
        digitalWrite(relayPin, LOW);
    }
    else if (SecondState == HIGH) {
        digitalWrite(relayPin, HIGH);
    }
    else {
        digitalWrite(relayPin, HIGH);
    }
}

Only else if (SecondState == HIGH) { works in output.
Schematics


texts: Humidity values returned by DHT22 sensors failing after some time

texts:
I've built a weather station using Arduino that measures temperature/humidity and pressure using an Adafruit 8266 HUZZAH. Temperature and Humidity are measured using a DHT22 sensor a ordered from AdaFruit. The project was completed about 4 months ago and for the first three months has returned what appears to be good data. Eventually, the humidity values started returning garbage, values around 1%.

I replaced the DHT22 sensor with another, this time from a random eBay seller. This also worked fine for about a week (humidity values appear to look good in the 20-60% range).

Then all of a sudden, they dropped to 1% again.

If I run the DHTtester program (instead of my program) against the sensor and my Uno development board, the result is also 1% humidity for this sensor.

 DHTxx test!
 Humidity: 1.00 %   Temperature: 19.20 *C 66.56 *F  Heat index: 17.96 *C 64.33 *F
 Humidity: 1.00 %   Temperature: 19.20 *C 66.56 *F  Heat index: 17.96 *C 64.33 *F

So at this point, I know the problem is not with my program (happens with both my program and the DHTtest program), not with my Arduino (happens with both the 8266 in "the field" and my Uno on my couch). So something must be happening to the sensors in the field, where they work for a week to a few months, and then fail?

Any ideas?

I'm beginning to think some bug/critter is eating or doing something to the sensor (maybe they are attracted to it because it's warmer), but anyway is there a good way to shield if this is the case without affecting the values? Any other way to see what is going on?

 // Example testing sketch for various DHT humidity/temperature sensors
 // Written by ladyada, public domain

 #include "DHT.h"
 #define DHTPIN 2     // what pin we're connected to

 // Uncomment whatever type you're using!
 //#define DHTTYPE DHT11   // DHT 11
 #define DHTTYPE DHT22   // DHT 22  (AM2302)
 //#define DHTTYPE DHT21   // DHT 21 (AM2301)

 // Connect pin 1 (on the left) of the sensor to +5V
 // NOTE: If using a board with 3.3V logic like an Arduino Due connect pin 1
 // to 3.3V instead of 5V!
 // Connect pin 2 of the sensor to whatever your DHTPIN is
 // Connect pin 4 (on the right) of the sensor to GROUND
 // Connect a 10K resistor from pin 2 (data) to pin 1 (power) of the sensor

 // Initialize DHT sensor.
 DHT dht(DHTPIN, DHTTYPE);

 void setup() {
   Serial.begin(9600);
   Serial.println("DHTxx test!");
   dht.begin();
 }

 void loop() {
     // Wait a few seconds between measurements.
     delay(2000);
     // Reading temperature or humidity takes about 250 milliseconds!
     // Sensor readings may also be up to 2 seconds 'old'
     float h = dht.readHumidity();
     // Read temperature as Celsius (the default)
     float t = dht.readTemperature();
     // Read temperature as Fahrenheit (isFahrenheit = true)
     float f = dht.readTemperature(true);

     // Check if any reads failed and exit early (to try again).
     if (isnan(h) || isnan(t) || isnan(f)) {
         Serial.println("Failed to read from DHT sensor!");
         return;
     }

     // Compute heat index in Fahrenheit (the default)
     float hif = dht.computeHeatIndex(f, h);
     // Compute heat index in Celsius (isFahreheit = false)
     float hic = dht.computeHeatIndex(t, h, false);

     Serial.print("Humidity: ");
     Serial.print(h);
     Serial.print(" %\t");
     Serial.print("Temperature: ");
     Serial.print(t);
     Serial.print(" *C ");
     Serial.print(f);
     Serial.print(" *F\t");
     Serial.print("Heat index: ");
     Serial.print(hic);
     Serial.print(" *C ");
     Serial.print(hif);
     Serial.println(" *F");
}


texts: What would be the best way to sense the tank level of a 1000L water tank?

texts:
I want to read in the values to an arduino analog input.

The approaches I have been looking at are:

1.) A ultrasonic distance sensor; my concerns are that tehse are not usually waterproof.

2.) A pressure transducer; these tend to be very pricy.

3.) Some kind of level switch which provides digital input (Is water level here: yes/no?)

Would anyone happen to have some advice on what sort of sensor would be good for the application of reading in the tank level and using the information in a sketch?


texts: Weird characters in Serial Monitor and not functioning ESP8266 ESP-12e

texts:
I did a bit of playing with my new ESP-12e, but suddenly it kind of fails on me. It gives me some weird looks it didn't give me (as much) before.

This is what the Serial Monitor prints when I try to run a very simple sketch. When I restart the module, it just adds some more of these chars.
The following is the code for that:

const int statusLED = 16;

void setup() {
  pinMode(statusLED, OUTPUT);
  digitalWrite(statusLED, HIGH);

  Serial.begin(115200);
  Serial.write("The ESP-12e has started.");
  delay(500);
}

void loop() {
  delay(1000);
  digitalWrite(statusLED, LOW);
  delay(1000);
  digitalWrite(statusLED, HIGH);
}

This doesn't even involve the WIFI...

These are my board settings:
Board: Generic ESP8266 Module
Flash mode: QIO
Flash frequency: 40MHz
CPU frequency: 80MHz
Flash size: 4M (3M SPIFFS)
Upload speed: 115200

And finally, if it might help, how I connected the module:

All connections are solid, so that shouldn't be a problem. The connection board has GPIO15 printed on it twice, but the one I connected to the LED is actually GPIO16. I noticed that the onboard LED of the ESP-12e doesn't light on anymore.

I use the CP2102 USB to UART module.

Thanks!
Rogier


texts: Navigating menus using buttons on Arduino

texts:
I have made a very short version of my code. It has the basic problem I am facing. I explain my code and problem below.

#include <Adafruit_RGBLCDShield.h>
#include <utility/Adafruit_MCP23017.h>
Adafruit_RGBLCDShield lcd = Adafruit_RGBLCDShield();

void setup() {
  lcd.begin(16, 2); //format of display
}

int menu = 0;
int subMenu = 99;
void loop() {

  uint8_t buttons = lcd.readButtons();

  lcd.setCursor(0,0);

  if (menu == 0) {
  lcd.print("Select menu option");
    if (buttons & BUTTON_SELECT) {
      lcd.clear();
      menu = 99;
      subMenu = 1;
    }
  }

  if (subMenu == 1) {
    lcd.print("in sub menu 1");
    if (buttons & BUTTON_SELECT) {
       lcd.clear();
       lcd.setCursor(0,1);
       lcd.print("shouldnt happen");
    }
  }
}

I am setting a variable menu, which will keep track of what main menu I am on, and a subMenu, which keeps track of what sub-menu I am on.

The default value of menu (0) prints on the LCD "Select Menu Option".

When pressing SELECT, the LCD is cleared. The menu is being set to an unknown number, so that it doesn't print anything, and subMenu is set to 1.

If subMenu is equal to 1 (which it will be if the user chooses presses SELECT), the LCD prints "in sub menu 1".

Inside this, if the button SELECT is clicked, it should print "shouldnt happen".

The issue I am facing is that when clicking SELECT for entering the menu 1, the SELECT is also carried out to the sub-menu, so instead of waiting for a second key press to confirm going into the sub menu, it goes straight into it.

This makes sense because it is check that SELECT has been pressed, prints a new page, with the button SELECT still having been pressed, so it validated the condition for key press in the sub menu as well.

The user input to LCD display response should be the following:

Select menu option -> presses SELECT -> in sub menu 1 -> presses SELECT -> shouldnt happen

Currently however, it is like this:

Select menu option -> presses SELECT -> in sub menu 1 shouldnt happen

How can I make it so that these key presses only act on the menu on which they are?

Thanks, let me know if something confuses you, I can explain in more details


texts: Is it possible to control a 12v led matrix with an arduino?

texts: This is a bit home automation but if I want to control my 12v LEDs and I have 8 free pins would it be possible to drive 16 lights as a matrix. I was looking into running 8 LEDs with an 8 channel relay but the I got to thinking if I wire up 16 LEDs in a matrix I could still control them all with those 8 channels. Problem is I was looking at mechanical relays that would burn out very quickly with that kind of switching. Are there any other solutions?


texts:
I am trying to read the value of an output pin. online forums say that digitalRead(pinNum); should work, but that is not the case here. digitalRead always returns 0 (LOW).
This is the code:

int pin = 22; // or 13, or 3 ...
void setup()
{
  Serial.begin(9600);
  pinMode(pin,OUTPUT);
}
void loop()
{
  digitalWrite(pin,HIGH);
  delay(100);
  Serial.println(digitalRead(pin));
  delay(100);
  digitalWrite(pin,LOW);
  delay(100);
  Serial.println(digitalRead(pin));
  delay(100);
}

printed values:

0
0
0
...


texts:
I want to define an unknown size for an array. However, I know that this cannot be done on the arduino. So what other methods do you suggest? I tried using vectors by downloading the library ArduinoSTL, but it doesnt work. (It only prints Serial.println(Signal); once, referring to the code in the pastebin link below)

Heres my code with vectors: https://pastebin.com/qBsRvk9Y


texts: I would like to ask if I can stack directly Adafruit PN532 RFID Shield onto my breadboard. Or do I need something for that? Thank you.


texts: Is it possible to use some sort of multitasking OS like ScmRTOS on Arduino based on Atmel 328 chip?


texts: Right PIN to activate a wireless relay with ESP8266 ESP-01

texts:
I'm trying to program an ESP8266 ESP-01 module to let it connect to my personal wifi network and activate a wireless relay that I've bought.

No problems with Wifi connection so I've omitted the code about it, my problem is to find what is the right PIN to set to LOW/HIGH to control my relay.
Setting relayPin to 1 as shown in this code works and with it I can see the embedded LED turning on and off.

const int relayPin = 1;

void setup() {
    pinMode(relayPin, OUTPUT);
}

void loop() {
    Serial.println("Close Relay for 100 ms and then Open");
    digitalWrite(relayPin, LOW);
    delay(100);
    digitalWrite(relayPin, HIGH);
    delay(200);
}

Surfing the web I've found the following diagram about the ESP8266 ESP-01 module:

I've tried to set relayPin to 0 or to 2 but the relay doesn't activate/deactivate.

So, what is the right PIN number to set in my relayPin constant to control the GPIO0 port?

The relay works succesfully if I give him +3.3V on GPIO0 with an external power.

Thanks in advance


texts: How to program for two Arduinos with different code but share one same .h?

texts:
I am now programming for two Arduinos. One is used as Tx and the other is Rx. Of course they are programmed by different codes, but they share some same .h files I programmed(let's say 'share.h'), which are not libraries and shouldn't be put in Arduino's 'library' folder.

So I put 'share.h' and main.ino in one folder, and the ino is like:

#include "share.h"
#define TX
#ifdef TX
void setup(){...something for Tx...}
void loop(){...}
#else
void setup(){...something for Rx...}
void loop(){...}
#endif

The shortage is that every time I want to update my code to the two unos, I have to: first change the board port to 40(the Tx uno) in ide, add the #define line, and upload. Then I have to change port to 42(the Rx one), comment the #define line and upload. So inconvenient!

So do you have any good ideas? Much appreciation!


texts:
When I remove the SD card and try to open a file, I can detect the error properly.

But how do I detect that the card has been replaced after an error? My first thought was to call SD.begin() again but it appears that this function returns true exactly once and false thereafter.

Simplified example:

void setup() {
  SD.begin(pin); // called exactly once. Works.
}
void loop() {
  // stuff
}

But this does not:

void setup() {
  SD.begin(pin); // first time calling this function: works.
}
void loop() {
  delay(1000);
  SD.begin(pin); // always fails
}

I'd rather not reset the microcontroller just for this.


texts: Need to "Extend" a Arduino Digital Signal

texts:
Here's the scenario:
We have 1 arduino uno accepting DMX and converting that to a signal that is being sent out digitally (PIN 3). The digital signal then goes to several IR LED senders that control 3,200 IR, color-changing candles. I've recently added some more senders, and now some of the senders are not working (even some that were working before). I assume this is because the digital signal has been weakened due to me splitting it so many times.

I'd like to add another arduino to control half of the IR senders. I obviously already have a cable running to every device, but I know of a perfect place to "interject" the new arduino. Is this possible? Can the second arduino essentially "repeat" or decode and re-encode the digital signal? If so, what pins am I looking at and will I need any special code?

Thanks for the help!


texts: Best way to send text to ESP8266 remote display

texts:
I need a remote display to show information sent via WiFi from another ESP8266. What needs to be sent is a string along with some variables, for example a string to be displayed along with two integers for the position on the display:

0, 12, "message to display on screen"

As I am absolutely new to network stuff, what would be the best way to achieve this?

Sending a POST request through REST API?
Use UDP instead?
Or better use a framework like MQTT?


texts: Essentially I am looking to build a remote controlled car using dc motors and one arduino uno to be on the car to supply the power logic and i wanted to use another arduino to be the remote. I was curious what the most effective method would be as to pairing these two devices in a way that it would provide the maximum range possible while still maintaining a decently high bandwidth limit. The reason for this is hopefully i can have the arduino mounted to the car connected to a camera where the camera would send a video feed over to the remote control. I was thinking about using a bluetooth module between the two such as a HM-10 but i wouldn't be able to send a video feed this way because bluetooth cannot transmit that much data at once. However if that is the most practical option i can get over the fact of not having a live video feed and send an image ever 5 seconds or so instead of live. Appreciate any insight on what the most effective method would be in terms of efficiency between range and data stream bandwidth.


texts: Getting stable measurements with the BNO055 IMU

texts:
I bought the BNO055 "smart" IMU from Adafruit, thinking it would be a simple way to get orientation data for a small mobile robot project, but I've found the thing to be very difficult to use and nearly worthless.

It's advertised as being able to auto-calibrate, and although it does attempt to do this, I've found that the calibration doesn't hold. It continuously re-calibrates itself, and either gets stuck in an error state or find a successful calibration...but then loses it after a few seconds.

Is there anything I can do to improve its stability? Does it need to be mounted inside a special grounded housing? Is there a special incantation I should utter before powering it on?

I'm reading it from an Arduino Uno via I2C, and though the wiring and programming is relatively simple, getting it calibrated and staying calibrated I've found to be nearly impossible.

Even after the "system" flag says its fully calibrated, and I have the IMU just sitting on a table, not moving, after a minute, it loses its "system" calibration. The accelerometer, gryoscope, and magnetometer usually remain calibrated, but how can I trust them if the on-board fusion algorithm is reporting it's not ready?

If the BNO055 is a lost cause, is there anything better? I've tried several MPU-**** chips from InvenSense, but they're even worse.


texts: Difference between Arduino IDE giving me headaches

texts:
For some time now I've been playing around with the latest version of Arduino IDE and my UNO and ATTiny with simple 433 RF links with the Manchester Library. It all worked fine, but for my next project I want to take the step up and use a better wireless thingy... like the nRF24l01 or the nfm12b.

And then starts the pain. Attiny does not have hardware serial, but people seems to have solved this by implementing software-serial. But then they have to use some other boards for ATTiny, because when I try to run the examples I get error messages that it could not find  and so on. I use the ATTiny boards I found over at google code.

Regarding the RFM12B I got something to compile. If I went back and downloaded Arduino IDE 1.5.0 (no other!) it actually work with the JeeLib - hurray! Why is this, why can't I use the latest version of the Arduino IDE?

Regarding the NRF24 chip this case is unresolved. I have not found the correct combination of boards, IDE and library versions. Could anyone point me in the right direction?

What are the difference between the Arduino IDE's? Why can I get stuff to work on 1.5.0 but not the latest 1.6.x?


texts:
I am (currently) parsing a PPM analog signal using an Arduino Uno R3 using the analog comparator ASCR and analog hardware interrupts using AIN0 and AIN1. I am applying a specific negative comparison voltage using a linear voltage regulator on AIN0 and the signal on AIN1.

Code snippets:

setup

  ACSR  = B00011011;

outside other closures

ISR(ANALOG_COMP_vect) {
   CRCArduinoPPMChannels::INT0ISR();
}

I am trying to move this project to an Arduino (compatible) Pro Micro from SparkFun. The datasheet specifies AIN0 on ATmega32u4 pin 1 but do not see a reference to AIN1.

The datasheet outlines use of the analog comparator on page 289:

  AIN+ can be connected either to the AIN0 (PE6) pin, or to the internal
  Bandgap reference. AIN- can only be connected to the ADC multiplexer.

I have connected the signal to Arduino pin 7, the comparison voltage to Arduino pin 20 (analog 2) and set the following options of the ADMUX register:

ADMUX = B11000101;

The interrupts trigger but the comparator voltage (AIN-) is not being observed. Any help would be appreciated.


texts:
I've been reading this post while trying to optimize the usage of the WiFi module on my ESP8266.

My main goal was to be able to connect/disconnect (respectively turn on/off) the WiFi module so I can optimize electricity consumption of the chip (I am trying to solar power it).

So, the way I integrated the proposed solution is as follows as I am no where calling deepSleep:

#include <RelayModule.h>
#include <ESP8266WIFI.h>
#include <rdm6300.h>
#include <string.h>
#include <ctime>

extern "C" {
    #include "user_interface.h"  // Required for wifi_station_connect() to work
}
/*...*/
#define RFID_PIN 13
#define RELAY_PIN 10
#define FPM_SLEEP_MAX_TIME 0xFFFFFFF
#define RELAY_OPEN_DURATION 6

RelayModule relay(RELAY_PIN);
Rdm6300 rdm6300;

int relayTurnedOnAt = 0;

void WiFiOn();
void WiFiOff();

void connectToWifi() {
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED)
  {
     delay(500);
  }
}

void setup() {
  connectToWifi();
  rdm6300.begin(RFID_PIN);
  /*...*/
}

void openFrontDoor() {
  WiFiOn();
  if(relay.isOff()){
    relay.on();
    relayTurnedOnAt = time(0);
  }

  /*Perform some business logic which makes a reference to Services hosted on the Internet*/
}

void lockFrontDoor() {
  relay.off();
  WiFiOff();
}

void loop() {
  // RFID TAG WAS SCANNED
  if (rdm6300.update()){
    openFrontDoor();
  }

  if (relay.isOn() && abs(time(0)-relayTurnedOnAt) > RELAY_OPEN_DURATION)
    lockFrontDoor();
}

void WiFiOn() {
    wifi_fpm_do_wakeup();
    wifi_fpm_close();

    //Serial.println("Reconnecting");
    wifi_set_opmode(STATION_MODE);
    wifi_station_connect();
}

void WiFiOff() {
    //Serial.println("diconnecting client and wifi");
    //client.disconnect();
    wifi_station_disconnect();
    wifi_set_opmode(NULL_MODE);
    wifi_set_sleep_type(MODEM_SLEEP_T);
    wifi_fpm_open();
    wifi_fpm_do_sleep(FPM_SLEEP_MAX_TIME);
}

The problem here is that once disconnected, I can not get the WiFi module connected back. I need to reset/restart the chip and then I get connected to the internet once again. I would like to be able to fully disable the module when not needed (and save power) and when I need it to submit some stuff to the internet - wake it up, do the job and then bring it back to suspended mode.


texts: Built-in capacitive touch detection with SAMD21 development board (Arduino Zero Compatible)

texts:
I bought this SAMD21 development board which shows up as an "Arduino/Genuino Zero (Native USB Port)" when plugged in. And I've successfully got a blink sketch running on it all good so far:

The reason I picked up this board was to experiment with the built-in capacitive touch sensor on the SAMD21. In the datasheet for this chip it claims to support a 'Peripheral Touch Controller with 256-Channel capacitive touch and proximity sensing'.

Does anyone know what this exactly means and how I would access this functionality to detect touches in my Arduino code? Obviously there are not 256 IO pins so how would this work? Is there some kind of internal multiplexer?

The 256 channel capacitive touch controller is also mentioned in a Sparkfun video about their SAMD21 board, so it must be possible to access this functionality.

Can someone direct me towards an Arduino library or method and more information on the wiring and pin connections for this. Thanks.


texts: Why Arduino Mega 2560 throw error when i try to upload example

texts:
I'm try to connect my Arduino Mega 2560 to PC, but I think it's not easy as I imagine. I spent a lot's of time to install USB driver. Here is a screenshot:

When I try to upload blink example, Arduino IDE throw this error:

Sketch uses 656 bytes (0%) of program storage space. Maximum is 253952 bytes.
Global variables use 9 bytes (0%) of dynamic memory, leaving 8183 bytes for local variables. Maximum is 8192 bytes.
avrdude: ser_open(): can't set com-state for "\\.\COM10"
avrdude: ser_drain(): read error: The handle is invalid."

Please help to run one simple example.

I think this screen may help to understand my problem:


texts: Guide to code for multitasking and non blocking timers

texts:
I'm beginning to do kind of sophisticated things (well.. for my entry level skill) and I have to control a display with 3 LED and 4/5 types of events and status.
I'm using the BlinkWithoutDelay example duplicating all the variables for different status/events but the code is really messy, full of puzzling nested if statements.
How to simplify the things? I don't know what to choose, because OOP could be a choice but I think it will hurt the low-memory thing inside the Arduino Uno/Leonardo. Interrupts could be another choice but I think they are like threads, and following the KISS principle I'd like to stay away from them.
So, can someone advice me some article/tutorial/code-to-read/whatever to understand how to use a lot of LEDs and keep a lot internal status without screw my brain?
EDIT:
It is a little bit hard to reproduce a simple skelton of my messy code, but it looks like this (in pseudocode maybe)
void loop() {
    if(state==0) handleState0();
    if(state==1) handleState1();
    if(state==2) handleState2();
    if(state==3) handleState3();
    readButtons();
    readSensors();
    …
}

// this is a block of variables that I have to copy-and-paste
// every time I have to blink a led (hoping that there is
// nothing blocking that can skrew up everything)
unsigned long previousMillis_1 = 0;
const long interval_1 = 1000;
int ledState_1 = LOW;

void handleState1() {
  // Green led blinking, yellow is fixed
  // this is a copy-and-paste code hard to maintain,
  // easily broken from any blocking call (like also I2C)
  // and hard to refactor or isolate
  unsigned long currentMillis_1 = millis();
  if(currentMillis_1 - previousMillis_1 >= interval_1) {
    previousMillis_1 = currentMillis_1;
    if (ledState_1 == LOW) ledState_1 = HIGH;
    else ledState_1 = LOW;
    digitalWrite(pinGreen, ledState_1);
    digitalWrite(pinYellow, LOW);
}

unsigned long previousMillis_2 = 0;
const long interval_2 = 1000;
int ledState_2 = LOW;

void handleState2() {
  // Yellow led blinking, green is fixed
  // same as before
  unsigned long currentMillis_2 = millis();
  if(currentMillis_2 - previousMillis_2 >= interval_2) {
    previousMillis_2 = currentMillis_2;
    if (ledState_2 == LOW) ledState_2 = HIGH;
    else ledState_2 = LOW;
    digitalWrite(pinYellow, ledState_2);
    digitalWrite(pinGreen, LOW);
}

void handleButtonPressed() {
  // this skrew everything and because is blocking
  // and should be inserted in the main loop with
  // some global variables: active/disable, counter,
  // and non-blocking vars like previousMills, interval, etc etc
  Serial.println("\ndisplayAccessDenied");
  for(int i=0; i<3; i++) {
    digitalWrite(pinRed, LOW);
    delay(100);
    digitalWrite(pinRed, HIGH);
    delay(100);
  } digitalWrite(pinRed, LOW);
}

I feel a little bit lost but all the Arduino example arounds are super simple and to make a middle-level LED interface I have to screw my minds with something that is not working as 100% and other than Arduino I find only super-hard articles on microprocessors with low-level C code. But the pasted example is not working at 100% AND super hard to read, maintain, etc.


texts: Configuring the registers of i2c AD converter ADS122C04

texts:
I am not able to set the configuration registers of the TI´s converter chip ADS122C04 using arduino MEGA via I2C.

The code mainly consists of the following:

1-reset the chip (one byte)

2-choose register (WREG) and set register data (figure 59 of the data sheet) for all four registers

3- start conversion (one byte)

In sum, ten (10) bytes are sent in one i2c frame using an array of bytes as follows:

  //--------------------------------------------------------------------

int ADR_THeiz_Austritt = 0x40;                                  //hex Adress of the device

byte InitArray[10] = {6, 64, 54, 68, 10, 72, 5, 76, 112, 8};    //configuration array

 Wire.beginTransmission(ADR_THeiz_Austritt);            //  talk to Slave

 Wire.write(InitArray,10);             // bytes array is sent to slave on ACK handshaking

  status = Wire.endTransmission();     //status as in
                              //https://www.arduino.cc/en/Reference/WireEndTransmission

  Serial.print("Status Initialisierung = ");

  Serial.println(status);

//--------------------------------------------------------------------

status is a byte, which indicates the status of the transmission:

0:success

1:data too long to fit in transmit buffer

2:received NACK on transmit of address

3:received NACK on transmit of data

4:other error

after configuration, when reading the value of e.g. register 0, the result was 0 (default) !!

A second attempt was performed with a for loop

     //--------------------------------------------------------------------

      for (int i=0; i<10; i++)

  {

    Wire.beginTransmission(ADR_THeiz_Austritt);

    Wire.write(InitArray[i]);

    //delay(10);

  status = Wire.endTransmission();

  Serial.print("status Initialisierung ");

  Serial.print(i);                      //print the array element no

      Serial.println(status);          //print the status of transmision

      }

  //--------------------------------------------------------------------

the print function outputs the following: 00, 10, 23, 30,43,50,63,70,83,90 which means:

i=0, InitArray[i]=6, status =0 --> Reset of chip successfull

i=1, InitArray[i]=64, status =0 --> adressing Register 0 successfull

i=2, InitArray[i]=54, status =3 -->  value for Register 0 not transmitted !! (the same applies for all registers)

i=9, InitArray[i]=8, status =0 --> start chip successfull

My question: why am I not able to put a value in the registers? what am I doing wrong?

would appreciate your support!


texts: How to read shiftOut function using arduino

texts:
(I'm sorry for my bad English, but I will do my best)

I have a Chinese MUC which already programmed. It communicates with a LED driver chip using three wires (STB,CLK,DIN).
(LED driver controls 16 digit 7 Segment display)

After some research, I found that it can be talk to LED driver using shiftout function.

Now the main coal is to connect these
 3 pins(STB,clk,din) to Arduino and read the incoming data and convert the data to numbers.

To test if this idea is working or not,
I came with two arduino (uno to send shiftout function  and mega to read it) after connect pin 2 of uno to pin 2 of mega and same 3 to 3, 4 to 4 and also Gnd of uno to Gnd of mega.
I wrote these codes:

arduino UNO side (to send shiftOut function)

    #define STB  4
#define clockPin  5
#define dataPin  6

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

  pinMode(STB, OUTPUT);
  pinMode(clockPin,  OUTPUT);
  pinMode(dataPin, OUTPUT);
}

void loop() {
 digitalWrite(STB, LOW);
    shiftOut(dataPin, clockPin, LSBFIRST, 0b10101010 ); // 1st digit
   digitalWrite(STB, HIGH);
}

arduino mega side (to read shiftOut function)

    #define STB 4
#define clockPin  5
#define dataPin  6

 int R_STB[8];
 int R_clockPin ;
 int R_dataPin ;
void setup() {
   Serial.begin(115200);

  pinMode(STB, INPUT);
  pinMode(clockPin,  INPUT);
  pinMode(dataPin, INPUT);
}

void loop() {

 R_STB = digitalRead(STB);
 R_clockPin = digitalRead(clockPin);
 R_dataPin = digitalRead(dataPin);

   for(int i=0 ; i<8;i++){
  Serial.print(R_STB[i]-2);

  Serial.print(" ");
  Serial.print (R_clockPin[i]);

 Serial.print(" ");
  Serial.print(R_dataPin[i]+2);
Serial.println(" ");
   }
 }

But the digital read at arduino mega side can't read all data due to it fast switching between High LOW statement maybe? and I am stuck here.

Please any one has any ideas?


texts:
Hi I am using an Arduino Mega 2560 with two sparkfun zx gesture sensors, two servos, 4 rgb leds strips and 4 light switches.

With the sensor, the code relies on interrupts, which interfere with the bahaviour of the servo and leds.

My knowledge of coding is limited so I am unsure of how to work around this, I think I have to introduce some new code.
interrupts leds and servos
However, I am unsure of how to introduce it.

Any help would be appreciated.


texts: Stabilizing output values of conductive sheet(Velostat) connected to analog pin A0 of Arduino

texts: I am trying to do some experiments with conductive sheet (velostat). When I apply a force on the sheet it should change the value of resistance(output). I taking the output of the sheet by connecting to analog input Ao of Arduino. But I am not getting constant readings from arduino, even if no pressure is applied. Do I need to build any extra circuitry to stabilize the output value? Can anyone please tell how to stabilize the output value of Arduino?


texts: ESP8266 still connects to wifi even after flashed with empty sketch

texts:
So, my wifi is a hotspot password protected. I was developing a program until I decided to comment the ssid and passwords from it, to prevent the ESP from connecting to the internet. But then it still connected. After some debugging, I decided to upload an empty sketch. It still connects to the hotspot!

What is going on?! How does it still know my SSID and password when loaded with an empty sketch!?


texts: Getting my keypad to reset when wrong password is entered

texts:
I am working on a puzzle for my nephew. I currently have an arduino mega, SD card reader and keypad. Everything is wired correctly and I have it currently programmed so when you enter the right password than an audio file plays and a green LED lights up. Where I am struggling is I do not know how to program it so that when the wrong pass code is entered then my red LED light flashes and the code resets to position 0. I also noticed that my current password is 1,2,3 and when I add a random number between my pass code, say, 1,5,2,3 or even 1,3,2,2,3 then the audio file still plays and my green LED lights up. Any suggestions?

#include <Keypad.h>
#include <SD.h>
#include <TMRpcm.h>
#define SD_ChipSelectPin 53

TMRpcm tmrpcm;
char* password = "123";
int position = 0;
const byte ROWS = 4;
const byte COLS = 4;
char keys[ROWS][COLS] = {
  {'1','2','3','A'},
  {'4','5','6','B'},
  {'7','8','9','C'},
  {'*','0','#','D'}
};

byte rowPins[ROWS] = { 8, 7, 6, 9 };
byte colPins[COLS] = { 5, 4, 3, 2 };
Keypad keypad = Keypad( makeKeymap(keys), rowPins, colPins, ROWS, COLS );
int R = 12;
int G = 13;

void setup(){
  pinMode(R, OUTPUT);
  pinMode(G, OUTPUT);

  LockedPosition(true);
  tmrpcm.speakerPin = 46;
  if (!SD.begin(SD_ChipSelectPin)) {
    return;
  }
}

void loop()
{
  char key = keypad.getKey();
  if (key == '*' || key == '#')
  {
    position = 0;
    LockedPosition(true);
  }
  if (key == password[position])
  {
    position ++;
  }
  if (position == 3)
  {
    LockedPosition(false);
  }
  delay(100);
}

void LockedPosition(int locked)
{
  if (locked)
  {
    digitalWrite(R, HIGH);
    digitalWrite(G, LOW);
    position=0;
  }
  else
  {
    digitalWrite(R, LOW);
    digitalWrite(G, HIGH);
    tmrpcm.setVolume(6);
    tmrpcm.play("matt.wav"); ;
    delay(10000);
    digitalWrite(G,LOW);
  }
}


texts: Did I accidentally short something? My Arduino UNO board does not communicate with the computer anymore

texts:
I had my sketch uplaoded and everything was working fine when I tried connecting one of the input pins(pre-configured as digital INPUT) to 12V, just to see if this was being read as a HIGH as well.
It seems to have done something and the board stopped working. Moreover, all pins seem to be stuck at HIGH!

So far Ive tried the following:

reset button: doesnt help
re-upload: doesn't work - it says not in sync

Physically nothing seems to be burnt/blown. What am I missing? Have I fried my board? I hope not. PS: It was connected to a 12V external power source

Any thoughts?


texts:
I want  to generate 10khz frequency on arduino uno pin 9 while reading analog pin A0 while running simulation from simulink model.
without programming arduino and without accessing timers and only basic arduino interface. can it be done


texts:
I was just going through this pressure sensor tutorial.

What I want to know is how can I set the exact altimeter in my readings depending upon my different geographical place ? or may be if I am attaching the sensor to my balloon.


texts: Plugged in shield off by one, now all analogues read high

texts:
I have a prototyping shield for an Arduino Uno. I accidentally plugged the shield into my arduino so that the pins were all "off by one". I didn't think this was possible, but it turns out that the extra pin just slips between the gaps in the pin headers:

I powered it on not realising. The arduino didn't show any LEDs, so I powered it down, saw my mistake, and plugged it all in again.

Now though A0-A5 are all reading high values (~900-1000 when I do analogRead(A0)), even when I have pulldown resistors on them, and they still read like that when I unplug my shield all together.

The digital writes all work perfectly.

I'm thinking that I've broken the Arduino. Is that possible, or could it be something else?


texts:
I messed around with the MAX7456 chip for a while, even the character set updating sketch seemed to work after a few modifications. But now it is not displaying anything with the Hello World sketch that worked before. No signal seems to pass through it, the screen is just black.

The datasheet says that one must write Video Mode 0 Register (VM0) at address 00H bit 1 to 1 via SPI to reset it, how would I do it? Also, how would one verify that the chip indeed did reset itself and responds to the commands given to it afterwards? (The board looks like this)


texts: Set the wall clock time or change GMT offset without ntp server?

texts:
I have been able to get the current time from an NTP server and set what appears to be an internal clock using the configTime() function from the ESP32 core.  I can then get the current time with the function getLocalTime().

I would like to be able to set the time returned by getLocalTime() from user input rather than from an NTP server.  I would also like to be able to update the GMT Offset without needing to reconnect to the server.

How do I interact with the clock value used by getLocalTime()? Is there documentation for this clock somewhere?

per request the SimpleTime example from the ESP32 install:

#include <WiFi.h>
#include "time.h"

const char* ssid       = "YOUR_SSID";
const char* password   = "YOUR_PASS";

const char* ntpServer = "pool.ntp.org";
const long  gmtOffset_sec = 3600;
const int   daylightOffset_sec = 3600;

void printLocalTime()
{
  struct tm timeinfo;
  if(!getLocalTime(&timeinfo)){
    Serial.println("Failed to obtain time");
    return;
  }
  Serial.println(&timeinfo, "%A, %B %d %Y %H:%M:%S");
}

void setup()
{
  Serial.begin(115200);

  //connect to WiFi
  Serial.printf("Connecting to %s ", ssid);
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
      delay(500);
      Serial.print(".");
  }
  Serial.println(" CONNECTED");

  //init and get the time
  configTime(gmtOffset_sec, daylightOffset_sec, ntpServer);
  printLocalTime();

  //disconnect WiFi as it's no longer needed
  WiFi.disconnect(true);
  WiFi.mode(WIFI_OFF);
}

void loop()
{
  delay(1000);
  printLocalTime();
}


texts: Program an ATMega328P and use it without Arduino board

texts:
I'd like to use an ATMega328P for my project, I hope to do it without the Arduino board.

I know with the Arduino IDE and an Arduino board I can program the microcontroller. However, would it be possible once I've programmed and debugged the program with Arduino IDE + Arduino board, to take away the microcontroller from the Arduino board and to use the ATMega328P separately, without the board?

If yes, what additional configurations I should do the ATMega328P to work correctly on the breadboard?


texts: Rc receiver giving wrong values when controlling servo

texts:
So I'm building a helicopter. That why I need a receiver (tgy 9x) to read the values from my controller. Those values get passed to my Arduino due where some calculation happen and then get sent to the servos.

Now the problem is the moment I move my servo all the value I get from my receiver immediately become gibberish.

The values I should get and get when I am not sending anything to my servos. These values are in microseconds.

Channel1 Channel2 Channel3 Channel4
1486     1484     1482     1472
1486     1484     1482     1472
1486     1484     1482     1472
1486     1484     1482     1472

What I get after moving the servo. These should be between 1000 and 2000.

Channel1 Channel2 Channel3 Channel4
1495     18660    1105     17182
1495     2337     5667     3070
8828     7674     8795     6198
10289    7674     8795     11404

The Arduino gets power from the USB (at the moment) and the servo from the ESC of my motor. All the grounds are connected. There is only one servo hooked up and all wires from the receiver are not anywhere near any power lines or servos.

So the question is why is the receiver giving me gibberish and how do I fix it.

Right now I have commented everything out except this:

RC_controller.h

#ifndef RC_controller
#define RC_controller

#include <Arduino.h>
#include "eeprom.h"

void RC_init();
void calc_input0();
void calc_input1();
void calc_input2();
void calc_input3();
void calc_input4();
void calc_input5();
#endif

RC_controller.cpp

#define RC_NUM_CHANNELS  8
uint32_t volatile rc_start[RC_NUM_CHANNELS];
uint32_t volatile rc_shared[RC_NUM_CHANNELS];
uint32_t volatile rc_raw[RC_NUM_CHANNELS];

int rc_channels_pin[8] = {2, 3, 4, 5, 6, 7, 8, 9};

void calc_input0() {
 int identifyer = 0;
   if (digitalRead(rc_channels_pin[identifyer]) == HIGH) {
     rc_start[identifyer] = micros();
   } else {
     rc_raw[identifyer] = (uint16_t)(micros() - rc_start[identifyer]);
   }
}

...

void RC_init()
{

 for (byte i = 0; i > RC_NUM_CHANNELS; i++)
   pinMode(rc_channels_pin, INPUT);

 attachInterrupt(digitalPinToInterrupt(rc_channels_pin[0]), calc_input0, CHANGE);
 attachInterrupt(digitalPinToInterrupt(rc_channels_pin[1]), calc_input1, CHANGE);
 attachInterrupt(digitalPinToInterrupt(rc_channels_pin[2]), calc_input2, CHANGE);
 attachInterrupt(digitalPinToInterrupt(rc_channels_pin[3]), calc_input3, CHANGE);
 attachInterrupt(digitalPinToInterrupt(rc_channels_pin[4]), calc_input4, CHANGE);
 attachInterrupt(digitalPinToInterrupt(rc_channels_pin[5]), calc_input5, CHANGE);
}

main.cpp

...
void setup()
{
Serial.begin(115200);
  Wire.begin();
#if I2CDEV_IMPLEMENTATION == I2CDEV_BUILTIN_FASTWIRE
    Fastwire::setup(400, true);
#endif
for (int a = 0; a < 3; a++)
  swashplate[a].attach(10+a, 1200, 1800);
RC_init();
}

void loop()
{
if (rc_raw[0] < 2000)
  {
    swasplate[0].write(rc_raw[0]);
  }

  Serial.print(rc_raw[0]);
  Serial.print("    ");
  Serial.print(rc_raw[1]);
  Serial.print("    ");
  Serial.print(rc_raw[2]);
  Serial.print("    ");
  Serial.print(rc_raw[3]);
  Serial.print("    ");
  Serial.print(rc_raw[4]);
  Serial.print("    ");
  Serial.print(rc_raw[5]);
  Serial.print("    ");
  Serial.println();
}


texts: Speed controller for Ceiling Fan 220V AC 100W

texts:
I would like to use ESP32 to speed control my AC ceiling fan which is 220V AC 100 W.

Will the below AC dimmer work with ESP32 to speed control the ceiling fan which is 220V AC 100 W?

If not, kindly suggest a commonly used PWN dimmer that works with ESP32 to speed control ceiling fan with 220V 100W?

This is the link to Speed controller available on Amazon.


texts: Simple compiler design help: Variable length arrays?

texts:
I'm trying to write a simple compiler in C++ for a language that I am making up for my lab.  The compiler will have to be able to turn a string like this:

"do command_one 3 times"

into a data structure that represents this:

<command_one>, <command_one>, <command_one>

it should also be able to turn something more complicated like this:

"do do c_one do c_two 2 times 2 times c_thr 2 times"

into a data structure that represents this:

<c_one> <c_two> <c_two> <c_one> <c_two> <c_two> <c_thr> <c_one>
                <c_two> <c_two> <c_one> <c_two> <c_two> <c_thr>

Another function will then read the commands out one by one.

These examples show all of the functionality that I would want from the compiler.

I'm having design issues for the compiler that I want to create.  Initially, I just wanted to do some string manipulation and turn the input string into an array of integers representing commands.  However, since the compiler will be outputting an arbitrarily large number of commands, and since arrays in C++ need to be initialized with a length, this could be a problem.

I am not fluent in C++ so I am hoping that a C++ whiz can show me a quick solution.  I have already come up with the suggested solution on my own in Python, however, my solution in Python has to do with the ability to change the length of lists on the fly.

EDIT: I am also intending to use this code for an Arduino, which supports C++ code but not the standard libraries.  I found the vector solution to work in my C++ code, but it will not work in the Arduino interface.  Is there a way to do the compiling WITHOUT using vectors?


texts: Mic input and Speaker output using arduino

texts:
I am trying to make a small project. Firstly, I want to record voice using a small microphone(electret) for the time button is pressed and on releasing the button, the speaker of my laptop should output the recorded voice or a speaker attached to the arduino should output.

Note: I don't want to use any shield to do so. Simply Arduino


texts:
I am trying to make an automatic lock which stays open during different times and on different days. I want the door open Monday through Friday 8am to 5pm. On Saturdays and Sundays I want the door locked. I will be using an electric lock strike the + wire to pin 9 and - to ground on arduino. I am using an LED for development purposes for now because I don't have the lock yet. The code I have now works (stays open) for 8am to 5pm through the whole week but i want the door locked for Saturdays and Sundays. This is my code so far:

#include <Time.h>
#define doorPin 9
void setup() {
  // put your setup code here, to run once:
  pinMode(doorPin, OUTPUT); // Connected to relay to activate the door lock
  setTime(10,1,1,6,7,2014);
}

void loop() {
if (hour()>=8 && hour()<=17){
  digitalWrite(doorPin, HIGH);
}
else if (weekday()==1 || weekday()==7){
  digitalWrite(doorPin, LOW);
}


texts: delay(time); vs if(millis()-previous>time); and drift

texts:
Going through an old project, I had code on two Arduino Due that looked like this

void loop()
{
  foo();
  delay(time);
}

taking to heart the majority of literature on using delay(); I recoded this as

void loop()
{
  static unsigned long PrevTime;
  if(millis()-PrevTime>time)
  {
    foo();
    PrevTime=millis();
  }
}

However, this seems to have created a situation where the two devices drift over a period of time when they didn't previously

My question is twofold:

Why would if(millis()-PrevTime>time) cause more drift than
    delay(time)?
Is there a way to prevent this drift without going back to delay(time)?


texts:
Looking to merge two different 2D arrays of different row sizes into one long array:
 int 2dArray1[][] = {
   {1, 2, 3},
   {4, 5, 6}};
 int 2dArray2[][] = {
   {10, 20},
   {30, 40}};
 int 1dLongArray[10];

This is where I need help in order to have the values of 1dLongarray be arranged as follows:
1, 2, 3, 10, 20, 4, 5, 6, 30, 40

How would I achieve this? Thanks in advance.


texts:
I’m trying to make a string of 300 Christmas tree lights where the colour of each of the lights is entirely controllable by my own code. I am a programmer so that side of things is the easy part as far as I’m concerned.

My researches so far have led me (no pun intended) to WS2811s driven by an Arduino. I prefer the look of these to the flat Adafruit-type ones. I don’t own an Arduino yet but have been dipping my toe into this site for quite a while now so am beginning to understand the basics.

I’ve established that I will need to have a fairly hefty 5volt power supply for the LEDs but that the Arduino itself can then run happily on its own USB supply.

Some of the things I’ve read seem to imply that the Arduino will struggle to process my program and supply the data to 300 LEDs at the same time, but it’s not clear what the problem will be. I assume each LED will continue to glow with the same colour until it receives the data for its next colour and the code for “Fire!” which then prompts all of them to switch to their next colour. Is this wrong?

I realise that 3 bytes per LED for 300 LEDs is a fair amount of data to keep having to send up the wire. I will also be having an array in the program to keep track of all 300 colour values.

Will this work? Can you offer any advice that might mean I don’t hit a brick wall somewhere when putting all this together?


texts: Unable to read the Serial Port through Arduino the way Serial Port Monitor softwares read it

texts:
I have a device feeding Rx Tx data every minute. I connected it to the computer. I downloaded a Serial Port Monitor Software, and here is the data I captured using that software.

Now when I try to capture the same data using Arduino, it captures something else as you can see in the image below. I tried reading it as hex, char, byte, unsigned int, but it just doesn't read the data properly.

Here I have provided my code. Can someone please identify the problem for me? I've been stuck on this for 2 weeks at least, and it is just not a good feeling! Any help will be much appreciated.

  Using Arduino Ethernet with microSD Card Slot

//#include <SoftwareSerial.h>
#include <SPI.h>
#include <SD.h>

static const int baud = 19200;
static const int chipSelect = 4;
static const int rx = 0;
static const int tx = 1;

File dataFile;
//SoftwareSerial serialPort = SoftwareSerial(rx, tx);

void setup() {

  Serial.begin(baud);     // opens serial port, sets data rate to 19200 bps
  while (!Serial) {
    ;
  }
  //serialPort.begin(baud);

 // pinMode(rx, INPUT);
 // pinMode(tx, OUTPUT);

   Serial.print("Initializing SD card...");

   if (!SD.begin(chipSelect)) {
       Serial.println("initialization failed!");
       return;
   }
   Serial.println("initialization done.");

   dataFile = SD.open("data.txt", FILE_WRITE);
   Serial.println("Data file created!");
   dataFile.close();
}

unsigned int incomingByte = 0;
void loop()
{
  if (Serial.available() > 0) {
                // read the incoming byte:
     incomingByte = Serial.read();
     Serial.print(incomingByte, HEX);
    }

  dataFile = SD.open("data.txt", FILE_WRITE);
  dataFile.println(incomingByte, HEX);
  dataFile.close();
}

  You can build the Serial Port Monitor software using C# Console App, here is the code for that:

using System;
using System.IO.Ports;
using System.Text;

class PortDataReceived
{
    public static void Main()
    {

        SerialPort mySerialPort = new SerialPort("COM3");

        mySerialPort.BaudRate = 19200;
        mySerialPort.Parity = Parity.None;
        mySerialPort.StopBits = StopBits.One;
        mySerialPort.DataBits = 8;
        mySerialPort.Handshake = Handshake.None;
        mySerialPort.RtsEnable = true;

        mySerialPort.Open();
        while (true)
        {
            string data = ReadData(mySerialPort);

            if (!string.IsNullOrEmpty(data))
            {
                Console.WriteLine(data);

            }
        }

    }

    public static string ReadData(SerialPort serial)
    {
        byte[] buffer = new byte[serial.BytesToRead];
        serial.Read(buffer, 0, buffer.Length);

        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < buffer.Length; i++)
            sb.AppendFormat("{0:X2} ", buffer[i]);

        return sb.ToString();
    }
}


texts: It is any DS2482 I2C to 1-Wire bridge functional library?

texts:
Please let me know if you know any good library for DS2482 I2C to 1-Wire bridge.
I tried to use https://github.com/cybergibbons/DS2482_OneWire library  but I got errors when I'm trying to run the library examples (Read_temp_sensors and Scan_1Wire_Bus):

Error for Read_temp_sensors:
Read_temp_sensors:2:10: fatal error: DallasTemperature.h: No such file or directory

Error for Scan_1Wire_Bus:
Scan_1Wire_Bus C:\Users\myuser\Documents\Arduino\libraries\DS2482_OneWire-master\OneWire.cpp: In member function 'uint8_t OneWire::waitOnBusy()':
C:\Users\myuser\Documents\Arduino\libraries\DS2482_OneWire-master\OneWire.cpp:121:3: error: 'delayMicroseconds' was not declared in this scope
delayMicroseconds(20);
^~~~~~~~~~~~~~~~~
exit status 1 Error compiling for board Arduino Nano.

Thank you


texts: Multiple buttons on single interrupt, how to debounce?

texts:
Buttons on separate interrupt pins work fine (triggered on FALLING), bouncing is handling by forcing a 80ms lockout period during which further presses are ignored. I like that solution for being lightweight.

My goal is to have 1 interrupt handle all events (buttons and other digital inputs). I don't want to depend on loop(), I wish to be free to use delay often rather than timer interrupts.
Most buttons execute an action when pressed, some, while pressed.

What I have now (just 2 buttons for now):

simulate this circuit – Schematic created using CircuitLab

void setup() {
  pinMode(17, INPUT_PULLUP);
  pinMode(16, INPUT_PULLUP);
  pinMode(3, INPUT_PULLUP);
  attachInterrupt(digitalPinToInterrupt(3), wotHappnd, CHANGE);
}

boolean isDebouncing(){
  unsigned int now = millis();
  if(now - time_lastPressed > time_debounceLockout){
    time_lastPressed = now;
    return false;
  }
  return true;
}

void wotHappnd(){
  boolean interruptFalling = digitalRead(3) == LOW;
  if(interruptFalling && isDebouncing()) return;
  // digitalRead the pins; do stuff
}

Internal pullups on all used pins.

My problem is that often (~4%), on interrupt, the interrupt pin is LOW all button pins are HIGH ("not pressed" - likely bouncing just as I read it). How to fix that?

Can't use delay during an interrupt; delayMicroseconds to wait for stable readout still feels inappropriate; a cap-based delay on the interrupt pin induces a period of floating.
Prefer solutions in software or with no more than 1 extra component per input.

[edit] here's a claim that pin interrupts do some filtering already, which, if true, may make some solutions unreliable.


texts:
I have simple example, where in loop is called webServer to handle clients and also text drawing on display.
The thing is that webServer is not responding, but when I remove second part of loop - drawing text to display then web server starts to work normally.

Server does not respond:

 void loop() {
      server.handleClient();
      unsigned long timeNow = millis();
      if ((timeNow > screenChangeTime))  {
          display.clear();
          display.setFont(ArialMT_Plain_16);
          display.setTextAlignment(TEXT_ALIGN_CENTER);
           display.drawString(12, 20,"Loaded: "+String(particles));
           screenChangeTime= timeNow + delay;
           display.display();
      }
    }

Server responds:

void loop() {
      server.handleClient();
}


texts: How to stop sending the last received char of UART echo function?

texts:
I developed a code for uart based ISR with linear buffers, the problem is that it keep sending the last received char in Arduino IDE.

Here's the application code:

#include "uart_new.h"

void setup() {
uart_init_new(103);
DDRB = 0xff;
}

void loop() {
uint16_t c;
c = get_char();
if (c & NO_DATA)
{
  PORTB |= (1<<PB5);
  _delay_ms(500);
  PORTB &= ~(1<<PB5);
  _delay_ms(500);
}
else
{
  put_char(c);
}
}

The header file:

#ifndef uart_new_H_
#define uart_new_H_

#define NO_DATA     0x0100
#define Buf_OF      0x0200
#define FR_Er       0x0400
#define DOR_Er      0x0800
#define PARTY_Er    0x1000

#define buf_s 32
#define buf_mask Buf_s - 1
#define baud_rate 9600

void uart_init_new(uint16_t ubrr);
void put_char(uint8_t data);
uint16_t get_char(void);
void put_s(uint8_t *str);

#endif // uart_new_H_

The source code:

#include <avr/io.h>
#include <Arduino.h>
#include "uart_new.h"

/*******************************************
If you want to prevent reading a string
backwards then you need FIFO implementation
*******************************************/

static volatile uint8_t rx_buf[32],tx_buf[32];
static volatile uint8_t rx_p,tx_p,rx_cnt,tx_cnt;
static volatile uint8_t rx_errors,tx_sBuf,rx_sBuf;

void uart_init_new(uint16_t ubrr)
{
    rx_p=0,tx_p=0,rx_cnt=0,tx_cnt=0;
    UBRR0H = (uint8_t)(ubrr>>8);
    UBRR0L = (uint8_t)ubrr;
    UCSR0B = (1<<RXEN0)|(1<<TXEN0)|(1<<RXCIE0); //Enable Rx and Tx & Receive interrupt
    UCSR0C = (1<<USBS0)|(3<<UCSZ00);            //Set frame format: 8data, 2stop bit
}

uint16_t get_char(void)
{
    if (rx_cnt == 0)
        return NO_DATA;
    else if (rx_p < rx_cnt)
        return rx_buf[rx_p++];
}

void put_char(uint8_t data)
{
    if (tx_cnt < 32)                        // start count the input data
        tx_buf[tx_cnt++] = data;            // 1st input location tx_cnt

        UCSR0B |= (1<<UDRIE0);
}

void put_s(uint8_t *str)
{
    while (*str)
        put_char(*str++);
}

ISR(USART_RX_vect)
{
    if (rx_cnt < 32)                        // start count the received data
        rx_buf[rx_cnt++]=UDR0;              // 1st output location rx_cnt
    else
        rx_cnt = 0;                         // when the counter reached max value, reset it, overwrite everything

if (!(UCSR0A & (1<<RXC0)))
        UCSR0B &= ~(1<<UDRIE0);
}
ISR(USART_UDRE_vect)
{
    uint8_t i;
    if (tx_p < tx_cnt)                      // check if pointer < counted data
        UDR0 = tx_buf[tx_p++];
        else
        {
            for (i=0;i<tx_cnt;i++)
                tx_buf[i]=0;
            tx_p = 0;                       // when the pointer reach max value, reset it
            tx_cnt= 0;                      // also reset counter for new transmission
            UCSR0B &= ~(1<<UDRIE0);         // disable empty data register interrupt
        }
}

If the there's a received char, then ISR is executed, the function exit the LED blink loop, but when the receive stops and there're no more data it doesn't return the blink state and keeps sending the last received char. How to solve this problem?


texts:
I am trying to build a unlocker on my hardlid for my ute. I have replaced the manual unlocking mechanism with 2 of these https://www.jaycar.com.au/slave-door-lock-actuator/p/LR8813.

Now my code below works sometimes and I cannot work out why. The way the code should work is

Press Unlock Button (Count increments)
Press Unlock Button again
When count = 2 turn relay on for 4 seconds then turn off
reset count to 0
If time between presses is longer than 10 seconds reset count to 0

Basic diagram below. Please note the push button is actually wired to a relay which is triggered by the car unlock remote and the LED is the actuators.

This is my code

int switchPin = 2; // choose the input pin (for a pushbutton)
int relayPin = 4; // choose the input pin (for a pushbutton)
int val = 0; // variable for reading the pin status
int counter = 0;
int currentState = 0;
int previousState = 0;
bool lockOn = false;

unsigned long currentMillis = 0;
unsigned long previousMillis = 0;

unsigned long LockcurrentMillis = 0;
unsigned long LockpreviousMillis = 0;

const long interval = 10000;
const long Lockinterval = 4000;

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

  pinMode(switchPin, INPUT); // declare pushbutton as input
  pinMode(relayPin, OUTPUT); // declare pushbutton as input

  Serial.println("Ready");
  Serial.print("IP address: ");

}

void loop() {

  currentMillis = millis();
  LockcurrentMillis = millis();
/*
  Serial.print("Current ");
  Serial.print(currentMillis);
  Serial.print(" | Previous ");
  Serial.println(previousMillis);
    //Serial.println(lockOn);

  Serial.print("Lock Current ");
  Serial.print(LockcurrentMillis);
  Serial.print(" | Lock Previous ");
  Serial.println(LockpreviousMillis);
  */
  if (lockOn == true){

    if (LockcurrentMillis - LockpreviousMillis >= Lockinterval) {
      // save the last time you blinked the LED
      LockpreviousMillis = LockcurrentMillis;
      digitalWrite(relayPin, LOW); // turn relayPin off
      lockOn = false;
      Serial.println("relay off");
    }
  }

  val = digitalRead(switchPin); // read input value
  if (val == HIGH) { // check if the input is HIGH (button released)
    currentState = 1;
  }
  else {
    currentState = 0;
  }
  if (currentState != previousState) {
    if (currentState == 1) {
      counter = counter + 1;
      previousMillis = currentMillis;   //reset timer
      Serial.println(counter);
    }
  }
  if (counter == 2) {
    counter = 0;
    digitalWrite(relayPin, HIGH); // turn relayPin on
    //delay(4000);
    //digitalWrite(relayPin, LOW); // turn relayPin off
    lockOn = true;
          LockpreviousMillis = LockcurrentMillis;

    Serial.println("relay on");
  }

  previousState = currentState;
  //delay(250);
  if (currentMillis - previousMillis >= interval) {
    // save the last time you presse the button
    previousMillis = currentMillis;
    //LockpreviousMillis = LockcurrentMillis;
    //if (counter >= 1) {
    Serial.println("Took too long reset count");
    counter = 0;
    lockOn = false;
    //}
  }
}

Any Help would be highly appreciated

Thanks


texts: How would I include Arduino libraries using AVR-gcc without the IDE?

texts:
I am writing my own code for the Arduino Uno. I compile my code with AVR-gcc, and then upload it with AVRdude. I am not using the Arduino software, but I do have it installed and working on my PC. I want to include some of the Arduino libraries in my project, like Wire.h for example.

I realise that I could either copy the source file to my current working directory or include the entire path, like: #include "/usr/share/arduino/libraries/Wire/Wire.h" but the issue with that is Wire.h includes Stream.h which includes Print.h which includes...you get the idea. These different libraries are not kept in the same place either. I would have to hunt up and down chains of files, copy them and then use them locally. This does not seem like a good option to me.

Including them like I normally would using the IDE doesn't work at all, which is not surprising.

So, how can I use these libraries in my project without all the pain of finding them manually?


texts: Problem assign float to an embed class within the Linked-list libary

texts:
I have successfully implemented some code which uses a linked-list.  Everything is working, except assigning a value to a float within the embeded class.  When I run the code below, I get the expected behavior, a flashing LED for 10 secs then LED turns continuously ON, and I also get the debug messages I expect.  However, when I comment the marked line to assign a value to the float, it still compiles, but the LED does not flash as expected and I get complete rubbish from debug.  I am using codebender on Chrome, and I have tried Firefox (both given same results).

Main Sketch https://codebender.cc/sketch:175995

Example of library working https://codebender.cc/sketch:176008

Can anyone help?

typedef void(*GF)(void);

#include "LinkedList.h"

class CsC {
    public:
        float PerS;
        GF FunctionToCall;
};

LinkedList<CsC*> TaskList = LinkedList<CsC*>();

void LEDON()
{
    digitalWrite(13,HIGH);
}
void after(float interval, String intervalDescription, GF func);

void after(float interval, String intervalDescription, GF func)
{
    float multi = 1;
    if(intervalDescription == "mins") multi *= 60;
    float delayMS = multi * interval;
    CsC *c;
    //Error if either of these lines uncommented
    //c->PerS=10000;
    //c->PerS=delayMS;
    c->FunctionToCall=func;
    TaskList.add(c);
    Serial.print(".");
}

void setup()
{
    Serial.begin(9600);
    pinMode(13, OUTPUT);
    Serial.println("Start write task list");

    after(35,"secs",LEDON);

    Serial.println("Done");
    Serial.println("Start prog");
}
void loop()
{
    Serial.print("List=");
    Serial.print(TaskList.size());
    while(TaskList.size()>0){
        CsC *c=TaskList.shift();
        long timeout=millis()+10000;
        //long timeout=millis()+((long)(c->PerS*1000.0));
        while(millis()<timeout){
            //To indicate it is running, and to save time, I have used a delay here
            digitalWrite(13,HIGH);
            delay(250);
            digitalWrite(13,LOW);
            delay(250);
        }
        c->FunctionToCall();
    }
    Serial.print(".");
    Serial.println("complete");
    while(1){}
}


texts: How to produce a .o file from code using Arduino IDE (primarily for LGPL3 compliance)

texts:
I spent a great deal of time looking for any posts regarding this and came up empty.

The reason I needed to do this is that I am working on some proprietary code that will be released in an embedded device, but makes use of an LGPL 3.0 licensed library which requires (4.d.0) that I release "corresponding application code in a form ... permit the user to recombine or relink the application with a modified version of the library."

Since the application is on an embedded device, the "corresponding application code" works out to the pre-link .o file which is normally well hidden in the Arduino process.


texts: How would you send clock impulses to a camera with an Arduino Mega?

texts:
Hardware newbie here and I need to know how to connect my TSL 1401 line scan camera to an Arduino Mega so that I can send it the needed impulses. The Mega has a hundred different sockets and the Schema just scared me when I looked at it.

I just want to know which socket I can connect to the CLK and SI ports of my camera so that I can get and an analog output of pixels.


texts: How to control segments with SevSeg library

texts:
The SevSeg library by Dean Reading seems to have a keyword to control individual segments on SSD's. I am using four common cathode, single digit displays. Does anyone know how to program individual segments?

#include "SevSeg.h";

SevSeg sevseg;

void setup() {
  // put your setup code here, to run once:

  byte numDigits = 4;
  byte digitPins[] = {2, 3, 4, 5};
  byte segmentPins[] = {6, 7, 8, 9, 10, 11, 12, 13};
  bool resistorsOnSegments = false; // 'false' means resistors are on digit pins
  byte hardwareConfig = COMMON_CATHODE; // See README.md for options
  bool updateWithDelays = false; // Default 'false' is Recommended
  bool leadingZeros = false; // Use 'true' if you'd like to keep the leading zeros
  bool disableDecPoint = false; // Use 'true' if your decimal point doesn't exist or isn't connected. Then, you only need to specify 7 segmentPins[]

  sevseg.begin(hardwareConfig, numDigits, digitPins, segmentPins,
    resistorsOnSegments,
    updateWithDelays, leadingZeros, disableDecPoint);

}

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

  sevseg.setSegments();
  //sevseg.setNumber(1234,0);
  //sevseg.setChars("");
  //sevseg.blank();
  sevseg.refreshDisplay();

}


texts: Detect low-frequency 'kicks' from analog jack music

texts:
I want to detect kicks / high-amplitude, low-frequency peaks in music coming from an RCA jack directly to an Arduino Uno analog pin. I've seen some tutorials online, but only managed to find stuff related to calculating the frequency on a sound which doesn't work for me.
Any ideas?


texts: I'm using ESP32 to read analogue pressure readings from this pressure transducer. My Problem is this sensor outputs 0.5V – 4.5V linear voltage output based on the pressure but ESP32 can only handle 0 - 3.3V in the ADC inputs. Can anyone advice me to how to accomplish this in 0 - 3.3V range?


texts:
I'm working to develop a simple code for MCP23017 that I want to use to run LCD128x64.

I was succeeded to set IODIRB as output and blink LED as a test.

Now I want to read the pin state, but I couldn't. Here's my code. I'm using the nice twi library that comes with Wire library.

uint8_t mcp23017_read(uint8_t add_reg){
    uint8_t data;
    twi_writeTo(MCP23017_ADD,add_reg,2,1,0);
    twi_readFrom(MCP23017_ADD,data,1,1);

    return data;
}

I've tried this version too:

uint8_t *mcp23017_read(uint8_t add_reg){
    uint8_t data[1];
    twi_writeTo(MCP23017_ADD,add_reg,2,1,0);
    twi_readFrom(MCP23017_ADD,data,1,1);

    return *data;
}

==================================================

Here's Arduino call function:

void loop() {
  // put your main code here, to run repeatedly:
  data = mcp23017_read(GPIOB);
  Serial.println(data);
  delay(100);
}


texts: I2c device disappear from bus after writing

texts:
I am currently experiencing a really odd I2C problem on a Atmega32u4 based card. I'm trying to use a TLV493D connected by I2C. I know from this thread that before using this device, I have to set the powermode :

Wire.beginTransmission(HallAddressWrite);       // Address the sensor
Wire.write(configReg);              // Address the Configuration register
Wire.write(powerMode);              // Set the Power Mode to Low
errorCode = Wire.endTransmission();             // Stop transmitting

But each time I'm trying to write on the TLV493D register, the device simply disappear from I2C bus ! I know it sounds strange, but I can demonstrate it with a modified version of default I2C scanner

if (error == 0)
{
  Serial.print("I2C device found at address 0x");
  if (address<16)
    Serial.print("0");
  Serial.print(address,HEX);
  Serial.println("  !");

  Serial.println("Beginning write test...");
  Wire.beginTransmission(address);
  // no register writing
  errorCode = Wire.endTransmission();
  Serial.print("Test ended with code : ");
  Serial.println(errorCode);

  Serial.println("SECOND Beginning write test...");

  Wire.beginTransmission(address);       // Address the sensor
  Wire.write(0x00);              // Address the Configuration register
  Wire.write(0x05);            // Set the Power Mode to Low
  errorCode = Wire.endTransmission();
  Serial.print("Test ended with code : ");
  Serial.println(errorCode);

  nDevices++;
}

which gives the output:

I2C device found at address 0x5E  !
Beginning write test...
Test ended with code : 0
SECOND Beginning write test...
Test ended with code : 0

And next scan doesn't find anything. As you can see, I don't lost my device when I don't write anything. But it disappears from my bus as soon as I write something (here, it's for setting low power mode, but any value will do the same).

More informations :

My code is correct. I know that because I don't have any problem when using an Arduino Uno or Arduino Mega. Unfortunately, I don't have an Arduino Leonardo to see if my problem comes from Atmega32u4.
My wiring is correct. I checked the signal on SDA and SCL pin on the TLV493D with an oscilloscope and everything is as expected : 3.3V and 100kHz.
I also have a SRF02 on my I2c bus : it is working as expected.
I don't think my TLV493D is damaged. In deed, I thought it was because of that. So I changed it for another one but the problem is still here.
I noticed than when beginning an I2C transmission at address 0x00, I am able to see my TLV493D again. But it is pointless since I have to set power mode again and thus, it disappears from bus once again.


texts: What is the best way to unit test my code without controller?

texts:
I want to unit test my Arduino code. Ideally, I want to execute and test my code without uploading it to the board. What tools or libraries can help me with this?

There is an Arduino emulator in development which could be useful, but it doesn't yet seem to be ready for use.


texts:
I installed the Arduino IDE 1.6.4, and used the "boards manager" to install the package for Arduino Due.

I am using c++11 in my project so i need to add the compiler.cpp.extra_flags=-std=gnu++11 like i did in the /Applications/Arduino.app/Contents/Java/hardware/arduino/platform.txt file (i am on MacOSX).
It seems that arduino is ignoring that file and using a configuration coming from somewhere else.

Where is the downloaded package installed? Can it be configured?


texts: ATtiny84A support with "Attiny" board manager installed to Arduino IDE

texts: Referring to page http://highlowtech.org/?p=1695, is it possible to program ATtiny84A as well, or just the chip version ATtiny84 (without "A")? Does anybody know?


texts: GSM library , sendSMS, string instead of char

texts:
I used the GSM library that comes together with arduino 1.
Specifically the sendSMS part.

I managed sucesfully to send SMS.

Now the thing is, inside this library the SMS to send is stored in a char variable:

char txtMsg[200];

My question is, are you able to send the SMS, but store the message not in a char variable, but as a String?

I would test it myself but now i only have one SIM card, and for some reason my network is blocking it (that is another thread to be started btw)


texts: VSCode Platformio Schedule.h: No such file or directory

texts:
I suppose this might be more an environment question regarding Platform.io and VSCode, as my code works great in the Arduino IDE, however the lack of syntax highlighting is driving me mad.

I've setup a Platform.io project in VSCode, copied my code across and setup my board (Wemos D1 Mini)

My platformio.ini file looks like:

[env:wemos_d1_mini32]
platform = espressif32
board = wemos_d1_mini32
framework = arduino

There are a couple of headers that are highlighted as having errors:

#include "FirebaseESP8266.h"
#include <ESP8266WiFi.h>

I've installed FirebaseESP8266 to my project from the PlatformIO libraries, however it still says:

  include errors detected. Please update your includePath. Squiggles are disabled for this translation unit
  (C:\Users\Greg\Documents\PlatformIO\Projects\Lovebox\src\main.cpp).C/C++(1696)

If I try to build it errors with src\main.cpp:1:22: fatal error: Schedule.h: No such file or directory

As for the ESP8266WiFi library, it simply says cannot open source file "ESP8266WiFi.h"

Anyone know where I'm going wrong?


texts: How I Can Send the status of switch in SMS by Arduino?

texts:
How I want help ,, I want send status of Switch If switch > 20 send SMS status of switch OFF and when switch <20 than mean switch ON , Don't want send the value of reading.
I use Arduino uno

If I want use multiple switch and send all status of switchs in one message.
I mean if switch1 > 20 ON and switch2 <20
I want send status of switch In one SMS
Switch1 ON
Switch2 OFF
Switch3 OFF

How I can do this??

void loop()
Switch = analogRead(S_Switch);
if (Switch > 20 )
{
Serial.println(Switch);// If Switch > 20 show in SMS switch statuse  OFF,, If switch < 20 show in SMS switch statuse ON
Serial.print("\n******************\n");
Sim900Serial.print("AT+CMGF=1\r"); //Sending the SMS in text mode
delay(1000);
Sim900Serial.println("AT + CMGS = \"+***************\"");//The predefined phone number
delay(1000);
Sim900Serial.println("MY Swicth statuse is :");
Sim900Serial.println(Switch); // I don't want the value of Switch I want ( ON , OFF )
 Sim900Serial.print("              ");
Sim900Serial.println((char)26);//the ASCII code of the ctrl z is 26
delay(5000);
Sim900Serial.println();
}


texts:
So hello everyone.
I'm creating simple menu with few sub menus,on my lcd screen. But i have run into small problem, i can't stay in my sub menu. When i press select button, it goes into submenu section and after maybe 1-2 sec it goes back to main menu.
#include <Wire.h>
#include <LiquidCrystal_I2C.h>

LiquidCrystal_I2C lcd(0x27, 16, 2);

int upButton = 10;
int downButton = 11;
int selectButton = 12;
int menu = 1;

void setup() {
  lcd.begin();
  lcd.backlight();
  pinMode(upButton, INPUT_PULLUP);
  pinMode(downButton, INPUT_PULLUP);
  pinMode(selectButton, INPUT_PULLUP);
  updateMenu();
}

void loop() {
  if (!digitalRead(downButton)){
    menu++;
    updateMenu();
    delay(100);
    while (!digitalRead(downButton));
  }
  if (!digitalRead(upButton)){
    menu--;
    updateMenu();
    delay(100);
    while(!digitalRead(upButton));
  }
  if (!digitalRead(selectButton)){
    executeAction();
    updateMenu();
    delay(100);
    while (!digitalRead(selectButton));
  }
}

void updateMenu() {
  switch (menu) {
    case 0:
      menu = 1;
      break;
    case 1:
      lcd.clear();
      lcd.print(">MenuItem1");
      lcd.setCursor(0, 1);
      lcd.print(" MenuItem2");
      break;
    case 2:
      lcd.clear();
      lcd.print(" MenuItem1");
      lcd.setCursor(0, 1);
      lcd.print(">MenuItem2");
      break;
    case 3:
      lcd.clear();
      lcd.print(">MenuItem3");
      lcd.setCursor(0, 1);
      lcd.print(" MenuItem4");
      break;
    case 4:
      lcd.clear();
      lcd.print(" MenuItem3");
      lcd.setCursor(0, 1);
      lcd.print(">MenuItem4");
      break;
    case 5:
      menu = 4;
      break;
  }
}

void executeAction() {
  switch (menu) {
    case 1:
      action1();
      break;
    case 2:
      action2();
      break;
    case 3:
      action3();
      break;
    case 4:
      action4();
      break;
  }
}

void action1() {
  lcd.clear();
  lcd.print(">Executing #1");
  delay(1500);
}
void action2() {
  lcd.clear();
  lcd.print(">Executing #2");
  delay(1500);
}
void action3() {
  lcd.clear();
  lcd.print(">Executing #3");
  delay(1500);
}
void action4() {
  lcd.clear();
  lcd.print(">Executing #4");
  delay(1500);
}

Thanks in advanced


texts: Writing Libraries that use libraries that are being used in the sketch

texts:
I know the title is a little obtuse, let me try to explain:
I am trying to create a library of simple functions for use with my TFT Panel.

The Panel has an include file (#include "SSD1306Wire.h")

I have a sketch and I have the above #include file referenced in the sketch
I also want to use my library tftHelper.h but that library needs to reference SSD1306Wire.h as well to get the helper functions to work.

Is there a way to reference SSD1306Wire.h one time and be able to use the reference in the functions in my helper library?

I guess, more importantly, what is the proper way to handle a situation like this?


texts: Connecting Arduino to PC through Slimline SATA instead of USB?

texts:
I removed the DVD-RW from my laptop and want to use the new area as an IO port instead. There is an Arduino Nano with me which can fit into the emptied out drive space and there are some easy to connect IO headers with me.

The only (major) problem is how can i connect the Arduino to the slimline SATA port of the DVD drive. There are some SATA to USB converters available in the market, but will they work? (as i am trying to connect it the other way around)

Is there any possible way to connect the Arduino to the SATA port, and even if i would be able to connect it, would i be able to use it as a regular Arduino as if it were connected to a USB port?


texts: Debouncing results in no reaction at all

texts:
Update:

I changed the code to this, but it does not work either.

`if ((millis() - lastDebounceTime) > debounceDelay) {

   if (button) {
 //DEBOUNCING

     if (!button_prev && button) {

      int e = input[j];`

I am trying to debounce a button and integrated this code http://arduino.cc/en/Tutorial/Debounce into my sketch.
The result is, that there is no reaction to the button at all.
I can't figure out the mistake, but maybe someone else sees what I overlook.

Circuit

Parts marked with //DEBOUNCING are only for the purpose of it, parts marked //DEBOUNCE relevant are necessary for the code to run as well when there is no debouncing.

void setup() {

  Serial.begin(9600);

  //setting button pin as input and LOW

  pinMode(8, INPUT);
  digitalWrite(8, LOW); //DEBOUNCE relevant

  //setting input pins as output

  int act_pin[6] = {A0, A1, A2, A3, A4};

  int k = 0;

  for (k = 0; k < 5; k++) {

      pinMode(act_pin[k], OUTPUT);

    }

  //setting state pins as output

  int z_pin[5] = {2, 3, 4, 5};

  int a = 0;

  for (a = 0; a < 4; a++) {

      pinMode(z_pin[a], OUTPUT);

   }

  //setting output pins as output

  int out_pin[6] = {9, 10, 11};

  int b = 0;

  for (b = 0; b < 3; b++) {

      pinMode(out_pin[b], OUTPUT);

   }

  //setting input

  for(k = 0; k < 5; k++) {

      randomSeed(analogRead(5));

      int i = random(2);

      if(i == 1){

         digitalWrite(act_pin[k], HIGH);

         input[k] = 1;

         Serial.print(input[k]);

      }

       else{

         digitalWrite(act_pin[k], LOW);

         input[k] = 0;

         Serial.print(input[k]);

      }

    }

   //setting initial situation

   digitalWrite(2, LOW);
   digitalWrite(3, HIGH);
   digitalWrite(4, LOW);
   digitalWrite(5, LOW);

   }

//DEBOUNCING

long lastDebounceTime = 0;  // the last time the button pin was toggled
long debounceDelay = 50;    // the debounce time; increase if the output flickers
int buttonState;

//DEBOUNCING

boolean button_prev = 0;

boolean button = 0;

int j = 0; //value shows current lamp being processed

//setting initial state

char z[4] = "z_0";

void loop() {

    button_prev = button;

    button = digitalRead(8); //DEBOUNCE relevant

    // DEBOUNCING
    if (button != button_prev) {

    lastDebounceTime = millis();

    }

    if ((millis() - lastDebounceTime) > debounceDelay) {

       if (button != button_prev) {
     //DEBOUNCING

         if (!button_prev && button) {

          int e = input[j];

           //provides a nice output
            Serial.println(" ");
            Serial.print("Current lamp being processed:");
            Serial.println(j);
            Serial.println(" ");
            Serial.print("Current input:");
            Serial.println(e);

             delta(e, z);

            Serial.print("State outside function:");
            Serial.println(z);

            lamda(e, z);

             j = (j+1) % 5;

      }

    }

   }
}


texts:
Hello I am using the u8glib library to draw text on the string but it keeps giving me an error with the string

 String name1 = "";
 ...
 void draw(){
  u8g.setFont(u8g_font_micro);
  u8g.drawStr(22, 37, name1);
 }

why dosnt this work?

Here is the error:

  C:\Program Files (x86)\Arduino\libraries\U8glib/U8glib.h:200:16: note:
  no known conversion for argument 3 from 'int' to 'const
  __FlashStringHelper*' no matching function for call to 'U8GLIB_PCD8544::drawStr(int, int, String&)'


texts: Can I use a 6 pin Bluetooth module in a 4 pin socket?

texts:
I have a Funduino joystick shield and it features a 4 pin bluetooth socket in the top right hand corner (just above the D, T, - and + legends).

For some reason, on eBay, 6 pin bluetooth modules are cheaper and more common than 4 pin bluetooth modules.

The joystick shield's 4 pin socket is labelled R T - +. Obviously these correspond with RXD, TXD, GND and VCC on the bluetooth module.

I was wondering:

What is the difference between the 4 pin and 6 pin modules?
Can I use a 6 pin module in the four pin socket on the joystick shield?
What is the function of additional STATE and EN pins on the bluetooth module?
Are these two additional pins necessary as other modules do not have them?


texts: Control relay with both Arduino and DAQ at the same time

texts:
I want to control a relay with both Arduino and DAQ. Arduino is used as an embedded  device for the control, while the DAQ is hooked up with a computer and performs the control with a user interface. Here is below a schematic of the circuit wiring for the control:

The two signal pins of the relay are connected with the digital pins of Arduino and DAQ. For some reasons, when Arduino comes into play, the control via DAQ cannot be achieved. If only Arduino or DAQ is connected to the relay, there is no problems with the control.

My plan here is, mstly, to let Arduino to instruct some tasks. In some special cases, I want to have the control with DAQ. Anyone can debug my circuit above? Thanks!


texts: 2.8 inch tft LCD displays / Max Brightness / Startup White Screen / mirror text for Head Up Display Usage

texts:
hi does anyone know how to

1) set Max Brightness
2) change the start up splash screen from being white to black
3) how to change settings so that text can be mirrored so when display is reflected into mirror or glass window the text reflects onto the mirror / glass so that it is readable

The code from the sketch may answer some of your tecnical question re the environment i am working with

#include <Adafruit_GFX.h>    // Core graphics library
#include <Adafruit_TFTLCD.h> // Hardware-specific library

#define LCD_CS A3 // Chip Select goes to Analog 3
#define LCD_CD A2 // Command/Data goes to Analog 2
#define LCD_WR A1 // LCD Write goes to Analog 1
#define LCD_RD A0 // LCD Read goes to Analog 0


texts: Making an automated watering system with Arduino

texts:
I am trying to make an automated watering system using an Arduino.

Here is my wiring diagram:

And here is my circuit wired up:

Here is the code that I'm using with Arduino. The code seems alright and the wiring on the Arduino seems okay as well, but I don't know where to place a speaker on the Arduino. The biggest problem is that the program doesn't run like I coded. After I uploaded this code to Arduino, the water pump just keeps running forever. Can anyone check up my code to make this run properly?

/**automated watering program **/

#include <avr/sleep.h>
#include <avr/wdt.h>
#define BEAT 300 // define time for the tone.
#define PINNO 12

int led = 13;

void setup() {
  // setup code to run once:
  pinMode(led, OUTPUT);
}

void loop() {
  // main code here, to run repeatedly:
  tone(PINNO,262,BEAT); // C(do)
  delay(BEAT);
  tone(PINNO,294,BEAT); // D(re)
  delay(BEAT);
  tone(PINNO,330,BEAT); // E(mi)
  delay(BEAT);
  tone(PINNO,262,BEAT); // C (do)
  delay(BEAT);
  tone(PINNO,294,BEAT); // D(re)
  delay(BEAT);
  tone(PINNO,330,BEAT); // E(mi)
  delay(BEAT);
  tone(PINNO,392,BEAT); // G(so)
  delay(BEAT);
  tone(PINNO,330,BEAT); // E(mi)
  delay(BEAT);
  tone(PINNO,294,BEAT); // D(re)
  delay(BEAT);
  tone(PINNO,262,BEAT); // C(do)
  delay(BEAT);
  tone(PINNO,294,BEAT); // D(re)
  delay(BEAT);
  tone(PINNO,330,BEAT); // E(mi)
  delay(BEAT);
  tone(PINNO,294,BEAT); // D(re)
  delay(BEAT);
  delay(1000); // Wait for 1 second
  digitalWrite(led,HIGH); //Make No. 11pin output HIGH = 5V
  delay(500); // Watering time
  digitalWrite(led,LOW); //Make No.11 pin output LOW = 0V
  // Shut down program to save battery using by watchdogtimer 24h standby mode
  int var = 0;
  while(var < 10800) {
    delayWDT(9); // 9seconds of shutdown
    var++; // 10800times repeat ＝24h
  }
}

void delayWDT(unsigned long t) {
  // delay excute while using powerdown mode
  delayWDT_setup(t); // watchdog timer setting
  ADCSRA &= ~(1 << ADEN); // ADEN bit clear and stop ADC
  set_sleep_mode(SLEEP_MODE_PWR_DOWN); // Powerdow mode
  sleep_enable();
  sleep_mode(); // sleep mode
  sleep_disable(); // WatchDog Timer times up and start working again
  ADCSRA |= (1 << ADEN); // turn on the ADC
}

void delayWDT_setup(unsigned int ii) {
  // setting up timer
  // 0=16ms, 1=32ms, 2=64ms, 3=128ms, 4=250ms, 5=500ms
  // 6=1sec, 7=2sec, 8=4sec, 9=8sec
  byte bb;
  if (ii > 9 ) {
    // get rid of strange numbers
    ii = 9;
  }
  bb =ii & 7;
  if (ii > 7) {
    bb |= (1 << 5);
  }
  bb |= ( 1 << WDCE );
  MCUSR &= ~(1 << WDRF); // MCU Status Reg. Watchdog Reset  Flag ->0
  // start timed sequence
  WDTCSR |= (1 << WDCE) | (1<<WDE); // allow to edit watchdog
  // set new watchdog timeout value
  WDTCSR = bb;
  WDTCSR |= _BV(WDIE);
}
ISR(WDT_vect) {
  // the work after time up, WDT
  //  wdt_cycle++;
}


texts: Unexpected results and hard crash when modifying and addressing arrays & variables within a struct

texts:
I'm trying to use a 2D array inside a struct on my arduino to store sensor readings. I'm having two main problems:

1: My Arduino is crashing and resetting when I try to access certain directories in my Array

2: My arraysize variable doesn't seem to be incrementing the way I'm expecting it to.

I've attached snippets of my code that I think are relevant.

struct calibration
{
  float NTU[];
  unsigned int readings[][28];
  unsigned int arraysize = 0;
};

//Main
void loop() {
  lcd.clear();
  lcd.setCursor(0,0);
  lcd.print("Waiting...");
  if (digitalRead(inputPin) == HIGH)
    TakeReadings();
  delay(50);
}

//after taking many readings from a sensor and averaging...

Calibration.readings[Calibration.arraysize][0] = average;
Calibration.arraysize++;
PrintMatrixToSerial();

//serial print function

void PrintMatrixToSerial() {
  Serial.print("1.9,1  3.8,1  7.5,1  15,1   30,1   60,1   120,1");
  Serial.println();
  for (int i=0; i<Calibration.arraysize; i++) {
    for (int j=0; j<7; j++) {
      Serial.print(Calibration.readings[i][j]); Serial.print("   ");
    }
    Serial.print('\n');
  }
}

When trying to assign values to my Calibration.readings array in certain directories, the Arduino hard crashes. For instance, a crash happens when the arduino tries to execute:

Calibration.readings[Calibration.arraysize][2] = average;

Secondly, after running my TakeReadings() function only once, I expect Calibration.arraysize to be equal to 1, therefore the PrintMatrixToSerial() function should only print one row of data; however, the serial monitor prints many rows. The following is an example of the output:

1.9,1  3.8,1  7.5,1  15,1   30,1   60,1   120,1

11   298   0   65292   779   1284   6
167   167   167   167   167   167   167
167   167   167   167   167   167   167
167   167   167   167   167   167   167
167   167   167   167   167   167   167
167   167   167   167   167   167   167
167   167   167   167   167   167   167
167   167   167   167   167   167   167
0   167   167   167   167   4245   40853
167   167   167   167   167   167   167
319   167   167   167   167   167   167

Is there an issue with my struct, or array declaration? I'm stumped at the moment, so any help would be appreciated.


texts: Change delay function to millis function to play music

texts:
I'd like to write a code by changing the delay function in the music playing code to the millis function, do you know how?
#include "pitches.h"

// notes in the melody:
int melody[] = {
  NOTE_C4, NOTE_G3, NOTE_G3, NOTE_A3, NOTE_G3, 0, NOTE_B3, NOTE_C4
};

// note durations: 4 = quarter note, 8 = eighth note, etc.:
int noteDurations[] = {
  4, 8, 8, 4, 4, 4, 4, 4
};

void setup() {
  // iterate over the notes of the melody:
  for (int thisNote = 0; thisNote < 8; thisNote++) {

    // to calculate the note duration, take one second divided by the note type.
    //e.g. quarter note = 1000 / 4, eighth note = 1000/8, etc.
    int noteDuration = 1000 / noteDurations[thisNote];
    tone(8, melody[thisNote], noteDuration);

    // to distinguish the notes, set a minimum time between them.
    // the note's duration + 30% seems to work well:
    int pauseBetweenNotes = noteDuration * 1.30;
    delay(pauseBetweenNotes);
    // stop the tone playing:
    noTone(8);
  }
}

void loop() {
  // no need to repeat the melody.
}