texts: Is it possible to count rising edges of a 4 MHz clock on an Arduino Due and trigger an interrupt like all 4'000'000 edges?

texts:
I am struggling with my Arduino Due and the Timer Counter functionallity. The following is what I am trying to achieve:

I want to execute a function to a specific point of time or more precisley after a specific amount of rising edges given by an external clock signal with a frequency of approx. 4 MHz. Thus I read the Atmel Datasheet, Section 36, Timer Counter. My approach was to trigger an interrupt every rising edge and increment a counter variable until I reached the desired amount of rising edges and call my function then. I can confirm that I am in fact counting rising edges with my current approach but I am reading way too slow. Is there any kind of register or hardware counter which automates the counting process. Like I set the register to a specific value and wait for an overflow, execute my function and reset the register? From my web research I found that this is possible on the Uno and Mega but I could not find anything for the Due and to be honest I am a bit overwhelmed by the Atmel Datasheet. Why not just use an Arduino Due or Mega then? I need the 3.3 Volts of the Due and from what I found the Uno and Mega are 5 V devices.

This is my code:

// define capture channels
#define CAPTURE_TC TC0
#define CAPTURE_CHANNEL 0
#define CAPTURE_IRQn TC0_IRQn
#define CAPTURE_Handler TC0_Handler
#define CAPTURE_ID ID_TC0
#define CAPTURE_PIN 2
#define CAPTURE_CLOCK_SELECTION TC_CMR_TCCLKS_TIMER_CLOCK3

// clock divisors corresponding to CAPTURE_CLOCK_SELECTION
static const uint32_t divisors[5] = { 2, 8, 32, 128, 0};

volatile uint32_t captured_pulses = 0;
volatile uint32_t captured_ra = 0;
volatile uint32_t captured_rb = 0;
volatile float frequency, duty_cycle, active_time;

/*
* Function:  setup
* ------------------------------------------------------------------------------
* Setup code. Will be executed once.
*/
void setup() {

  // init serial connection
  Serial.begin(115200);
  Serial.print("Initializing...");

  // configure the PIO pin as peripheral
  const PinDescription *config = &g_APinDescription[CAPTURE_PIN];
  PIO_Configure(config->pPort, config->ulPinType, config->ulPin, config->ulPinConfiguration);

  // enable timer peripheral clock
  pmc_enable_periph_clk(CAPTURE_ID);

  // configure the timer
  TC_Configure(CAPTURE_TC, CAPTURE_CHANNEL,
    CAPTURE_CLOCK_SELECTION   // Clock Selection
    | TC_CMR_LDRA_RISING      // RA Loading: rising edge of TIOA
    | TC_CMR_LDRB_FALLING     // RB Loading: falling edge of TIOA
    | TC_CMR_ABETRG           // External Trigger: TIOA
    | TC_CMR_ETRGEDG_FALLING  // External Trigger Edge: Falling edge
 );

  // configure TC interrupts
  NVIC_DisableIRQ(CAPTURE_IRQn);
  NVIC_ClearPendingIRQ(CAPTURE_IRQn);
  NVIC_SetPriority(CAPTURE_IRQn, 0);
  NVIC_EnableIRQ(CAPTURE_IRQn);

  // enable interrupts
  CAPTURE_TC->TC_CHANNEL[CAPTURE_CHANNEL].TC_IER = TC_IER_LDRBS;

  // start timer counter
  CAPTURE_TC->TC_CHANNEL[CAPTURE_CHANNEL].TC_CCR = TC_CCR_CLKEN | TC_CCR_SWTRG;

  Serial.println("ready!");

} // setup

/*
* Function:  loop
* ------------------------------------------------------------------------------
* Loop code. Will be executed repeatedly after setup completed.
*/
void loop() {

 // Serial.print("Captured rising edges: "); Serial.println(captured_ra);
} // loop

/*
* Function:  CAPTURE_Handler
* ------------------------------------------------------------------------------
*
*/
void CAPTURE_Handler() {
 if ((TC_GetStatus(CAPTURE_TC, CAPTURE_CHANNEL) & TC_SR_LDRBS) == TC_SR_LDRBS) {
   captured_pulses++;
   // captured_ra = CAPTURE_TC->TC_CHANNEL[CAPTURE_CHANNEL].TC_RA;
   // captured_rb = CAPTURE_TC->TC_CHANNEL[CAPTURE_CHANNEL].TC_RB;

   if (captured_pulses == 4164303) {
    captured_pulses = 0;
    // specific_function_call();
   }
 }
} // CAPTURE_Handler

Thanks for your time, any help is grealty appreciated.


texts: pin going high not allowing analog read to change

texts:
I have the following problem:

My arduino takes analogRead(A0) from a potentiometer whose position I can't adjust directly.

When analogRead(AO) goes to a value X,  I want pin 8 to go HIGH, this causes the circuit to open. and stop A0 getting higher . so I do an if statement:

if(analogRead(AO)> X) {

digitalWrite(pin, HIGH)  \\opens the circuit}

else {
digitalWrite(pin, LOW)  \close the circuit
 }

The issue I have here, is when then circuit is open,  I would like to change the value of the potentiometer (A0) which is controlled by a motor which is also in the circuit: but doesnt depend on the arduino board.  Given I can't control A(0) then the circuit will remain on A(0) >X forever.

The system going to LOW pin or close circuit, after it reaches HIGH pin for 2 seconds would be great, but then the program goes to the beginning and realizes that still A(0)> X , and goes back to a open circuit state, therefore not allowing me to have the close circuit anymore in order to make A(0) < X  and leave the circuit closed . Maybe something that cyclically turns pin on an off for t mseconds? but this is not ideal as it would cause high wear on the system

Edited the post to be more precise. I hope now its clearer
thanks

thank you for your answers, but after playing for a while with your codes, and the ideas behind it, still cannot get it to work.

for instance, Chrisl with your first:

when potentiometer is at > X, It cuts the circuit which is good, but still doesn't go off until both potentiometer goes to < X and 3 seconds lapse , but this is not going to be possible to achieve anyways    because the value of the potentiometer is fixed on X

THis is what Id need-

if (PinState == HIGH)

after 3 seconds go low,

and not turn HIGH until at least these two conditions are met; analogRead has gone to < X and then analogRead > X ,and in that moment we are back at
PinState HIGH
is  even possible to achieve something like this?

the circuit is something like this:

simulate this circuit – Schematic created using CircuitLab

UPDATE:
I have using this code, which does almost what I want:
         if(analogRead(A0) > X) {
      unsigned long currentMillis = millis();

if ((unsigned long)(currentMillis - previousMillis) >= interval) {

   pinState = !pinState;
   digitalWrite(pin, pinState)
   // save the "current" time
   previousMillis = millis();
}}

When it gets to analogRead(A0)> X the problem of this code is that it switches the pin On and OFF continuosly,

but instead of switching it off/on after the interval time , I want it to be LOW always. Of course as long as time  is more than interval,and not get to a HIGH, until It has gone back to  analogRead(A0)> X and time is less than interval. And repeat the process... When time is more than interval it will go from where it was digitalWrite(pin, HIGH) to the new state digitalWrite(pin, LOW)

I made this table to be more clear

Table: analogRead(A0) > X?

1-yes -->now check if time in this state is less than interval = 3000:

1.1-YES, ---> digitalWrite(pin, HIGH)
   1.2- if no ( time is more than interval ) --->  digitalWrite(pin, LOW)

2-  No, analogRead(A0) < X . So -->  keep  digitalWrite(pin, LOW)

NEW UPDATE:

The state diagram for the new ranges should be something like this. I hope it is clear. I also removed the delays and replaced  (V < X ) for (V < Y )  , it works great. Thank you Edgar.

Z in the diagram being the variable for the new range, Z << X

LAST UPDATE:

Question Solved by Edgar Bonet


texts: Using a water sensor with a NodeMCU make it less sensitive?

texts:
I'm trying to digitalRead from a water sensor (the one in the picture) using NodeMCU v3,when I try the sensor with an Arduino board it works fine, but when I try it with an ESP8266 NodeMCU v3 it becomes less sensitive to water with some pins or doesn't work at all with the others. My question is: Is that normal or I'm doing something wrong ?

 int pin = 14;
 char printBuffer[128];
 int ledPin = 12;
 const int buzzerPin = 13;

  void setup()
  {
    pinMode(pin, INPUT);
    pinMode(buzzerPin, OUTPUT);
    pinMode(ledPin,OUTPUT);
    Serial.begin(115200);
  }

  void loop()
  {
    sprintf(printBuffer,"PIN %d level is %d\n",pin, digitalRead(pin));
    Serial.print(printBuffer);
    if (digitalRead(pin)==HIGH)
    {
      tone(buzzerPin, 100,1000);
      digitalWrite(ledPin, HIGH);
      delay(100);
      noTone(buzzerPin);
      digitalWrite(ledPin, LOW);
      delay(100);
      Serial.println("----------- ALARM ACTIVATED -----------");
    }
    else{
      noTone(buzzerPin);
      digitalWrite(ledPin, LOW);
    }
    delay(500);
   }


texts: let me describe my schema, i got one arduino and one esp32 connected over i2c using 30m cat 5e ftp cable, I'm using 12v to power up both devices, each of them have dc-dc converter that convert to 5V, there is two P82B715P extenders, controllers i2c bus is wired with 10K pullups to P82B715P , i2c bus between P82B715P is wired with 1K pullups on master device side. On 30M cable it works only if I transmit SDA, SCL in twister pair with ground, no power voltage (+12V) is on the cable. When I place +12V on the cable, I2C bus stop working, tried to decrease pullups to 0.4K no effect, since I do not understand can only make try/fail tests. Question is do I need to adjust pullups beween P82B715P only,  or I need to change pullups between P82B715P and esp/arduino? Perhaps for calculation of pullups I must mention that i2c bus work on 10KHz


texts: Decreasing Arduino pro micro power consumption

texts:
I'm working on a project that involves sending GPS coordinates wirelessly from an arduino board to another one. I was thinking of using an arduino micro for this task. The problem is that I want it to last as long as possible on a lithium battery. I searched and found too many tutorials on how to decrease arduino pro mini power consumption, but I didn't find anything related to the arduino pro micro. So I was thinking, does the same procedure used to decrease the arduino pro mini consumption apply for the arduino pri micro?
Also, what microcontroller do you suggest for this project? (PIC, Arduino mini, micro, nano...)


texts: Is there a non-float alternative to pow()?

texts:
I've scoured the LANGUAGE REFERENCE in the Arduino web-site, and I can't find a non-Float equivalent to pow()  I've got to be missing something big, but for the life of me, I'm stumped!  I found pow() in the FUNCTIONS column under the Math heading (like I would expect), but it says that both parameters,  [base] and [exponent] are both (float). And there are only six other entries under the Math heading; none of them seem to be seem to be an integer version. All I want to do is generate the powers of 2 using the exponents from 0 to 10. Like 2^0=1 then 2^1=2 then 2^2=4 then 2^3=8 then 2^4=16 then 2^5=32 then 2^6=64 then 2^7=128 then 2^8=256 then 2^9=512 then 2^10 is 1024

Is using floats the only way I can do this? I'm starting to feel like I'm at odds with reality, and have actually counted my medication, but I'm right where I should be. Let me apologize in advance for this egregious oversight that I've wasted your time with, but I've gone through all 9 pages of tags and have done ever search I could think of. I'll admit that I haven't spent all THAT much time, but I was sure this was only going to be like a five minute thing!


texts:
To reduce the components amount I don't want to put the  32.768 kHz oscillator on my own Due.
Can I leave the corresponding XTAL inputs unconnected?

What is the main target of the slow clock?
What I can not do with the high clock but can do with the slow one?
Will I face to any issues if I don't use the low freq. oscillator?


texts: Is there a more elegant way to check highest / lowest sample data?

texts:
N00b question,

Is there a better way for readability / elegance / DRY etc to check various sensor values for high/low record value?  This code works, but looks like the long way round.

  void checkRecord() {

if ( temp.current > temp.high) {
  temp.high = temp.current;
}

if ( temp.current < temp.low) {
  temp.low = temp.current;
}

if ( pressure.current > pressure.high) {
  pressure.high = pressure.current;
}

if ( pressure.current < pressure.low) {
  pressure.low = pressure.current;
}
if ( humidity.current > humidity.high) {
  humidity.high = humidity.current;
}

if ( humidity.current < humidity.low) {
  humidity.low = humidity.current;
}

if ( rainfall.current > rainfall.high) {
  rainfall.high = rainfall.current;
}

if ( rainfall.current < rainfall.low) {
  rainfall.low = rainfall.current;
}
if ( altitude.current > altitude.high) {
  altitude.high = altitude.current;
}

if ( altitude.current < altitude.low) {
  altitude.low = altitude.current;
}
}

Thanks!


texts: Arduino screws up trivial program involving enum

texts:
Behold this insanity:

enum WhatArduinoIs {
  Easy, But, Insane, Obsolete, And, Far, Worse, Than, mBed
};

void TellMe(WhatArduinoIs pls) { }

void setup() { }
void loop() { }

I'm pretty good at C++, so I'm fairly sure that should compile. However I get this error:

sketch_jan21b.ino:3:13: error: variable or field 'TellMe' declared void
sketch_jan21b.ino:3:13: error: 'WhatArduinoIs' was not declared in this scope
Error compiling.

I've encountered the Arduino "IDE"'s propensity for insane and totally unrobust modification of programs before. Specifically when you #include libraries Arduino only magically adds the relevant C++ files if the #include is in your main sketch. #include <LiquidCrystal.h> in another C++ file? Link errors.

I suspect in this case it is Arduino magically trying to add function declarations to the start of the file so their order doesn't matter. I.e. it turns the file into this:

void TellMe(WhatArduinoIs pls);

enum WhatArduinoIs {
  Easy, But, Insane, Obsolete, And, Far, Worse, Than, mBed
};

void TellMe(WhatArduinoIs pls) { }

void setup() { }
void loop() { }

That obviously doesn't work. How can I tell Arduino to leave my damn program alone?


texts: NodeMCU with digital sound sensor - Can't find examples or good documentation

texts:
I'm very new to this world, and trying to hack one of my first projects have proven hard without solid documentation or examples to copy like I usually do.

I've got a https://www.gearbest.com/transmitters-receivers-module/pp_366523.html NodeMCU ESP8266 board that I'm trying to pair with a Sound Sensor. I wanted digital and simple solution, but I'm thinking I might need a library to make it work?

The closes examples I've found are DHT11/22-sensors using the DHTlib library.

The Waveshare-Wiki contains the following expample that I've tried to modify without any luck.

int sound_din=2;
int sound_ain=A0;
int ad_value;
void setup()
{
  pinMode(sound_din,INPUT);
  pinMode(sound_ain,INPUT);
  Serial.begin(9600);
}
void loop()
{
  ad_value=analogRead(sound_ain);
  if(digitalRead(sound_din)==LOW)
  {
    Serial.println("Noise!");
    Serial.println(ad_value);
  }
  else
  {
    Serial.println("Quiet!");
  }
  delay(500);
}

I've also tried to modify/simplify this code to just print the digital output:

#include <ESP8266WiFi.h>

int dig_in=4; //Using D2-pin on my NodeMCU-board
int dig_value;

void setup()
{
  pinMode(dig_in,INPUT);
  Serial.begin(115200);
}

void loop()
{
  Serial.println(digitalRead(dig_in));

  delay(1000);
}

This results in varius gibborish and junk. I've seen plenty of various errors, and the board seems to crash quite a lot. I've tried swapping out the NodeMCU and the Sound level sensor with new ones, but still seem to be getting the same problems.

Any pointers? Thanks!

UPDATE: I've gotten further by using the following code from this example:

// Program: Sound Level Measurement
#include <ESP8266WiFi.h>

int num_Measure = 1280 ; // Set the number of measurements
int pinSignal = A0; // pin connected to pin O module sound sensor
long Sound_signal;    // Store the value read Sound Sensor
long sum = 0 ; // Store the total value of n measurements
long level = 0 ; // Store the average value

void setup ()
{
  pinMode (pinSignal, INPUT); // Set the signal pin as input
  Serial.begin (74880);
}

void loop ()
{
  // Performs 128 signal readings
  for ( int i = 0 ; i <num_Measure; i ++)
  {
   Sound_signal = analogRead (pinSignal);
    sum =sum + Sound_signal;
  }

  level = sum / num_Measure; // Calculate the average value
  Serial.print("Sound Level: ");
  Serial.println (level);
  sum = 0 ; // Reset the sum of the measurement values
  delay(1000);
}

The result is an output that seems to be pretty close to the relative sound level in the room. I've got a couple of issues that I'm still working on:

NodeMCU randomly crashing. The stacks are not exactly alike, but I've copied one of them down below. I've yet to decode this.
Pretty high noise floor. I.e. anything below around 60dB reads as 3/4/5. I've got to test this some more, it might just be the microphone is not sensitive enough.

  Exception (0):
  epc1=0x40103861 epc2=0x00000000 epc3=0x00000000 excvaddr=0x00000000
  depc=0x00000000

  ctx: sys
  sp: 3ffffcd8 end: 3fffffb0 offset: 01a0

  stack
  3ffffe78:  3fffc200 00000022 00000000 03c4345f
  3ffffe88:  00000000 4000050c 3fffc278 4010268c
  3ffffe98:  3fffc200 00000022 3ffffeb0 00000000
  3ffffea8:  000002ea 00000000 40000f68 00000030
  3ffffeb8:  0000001e ffffffff 40000f58 00000000
  3ffffec8:  00000020 00000000 3ffe91f0 c06301dc
  3ffffed8:  3ff20a00 c0000000 00003000 00000000
  3ffffee8:  00000058 3fffdab0 00000000 3fffdcc0
  3ffffef8:  3ffe8b88 00000030 00000000 00000000
  3fffff08:  00000020 40101612 3ffe8ae0 40203ebb
  3fffff18:  3fff01ac 40106fb4 00000000 40208a24
  3fffff28:  3ffed518 40222a2d 3ffef904 3ffef900
  3fffff38:  01331819 40105e3e 00000000 00000000
  3fffff48:  60000600 00000100 00000058 00000001
  3fffff58:  4010483a 3ffecc60 3fff01ac 401011a6
  3fffff68:  00000001 00000000 402187a8 40100f73
  3fffff78:  00000000 00000000 40100fae 00000000
  3fffff88:  00000002 3fffdcb0 40203b76 3fffdab0
  3fffff98:  00000000 40202303 3ffe8b88 40000f49
  3fffffa8:  3fffdab0 40000f49 40000e19 40001878
  stack


texts:
In the project I am working on, I have a limited space with which I can work. I am using an Arduino Uno with 2 Adafruit motor shields, and when I stack them using normal, female stacking headers it is too tall to fit. I thought that one way to solve this would be to lay them out side to side rather than one on top of the other. So, instead of this

+--------Motor shield 2 ----------+
|||||||||||||||||||||||||||||||||||
+--------Motor shield 1 ----------+
|||||||||||||||||||||||||||||||||||
+---------Arduino Uno ------------+

it would look like this

               -----------------------------------------Wires -------------------------------
+---------Arduino Uno ------------+    +--------Motor shield 1 ----------+    +--------Motor shield 2 ----------+

Would this be possible if I were to connect all of the pins with wires, and has anyone successfully done this before?


texts: Powering potientiometer/button with a digital pin

texts:
When I read articles/tutorials about the Arduino Uno, the potentiometer and button always get power from the 5 V pin instead of from digital pins.

May I know whether the two components above can be powered by digital pins?

What is the situation that the components must only get power from 5 V pin instead of digital pins?


texts: Are there any constants for default SPI port pins defined?

texts: I'm writing a library which controls a device using SPI bus. For the communication I need to manually toggle the chip select pin. On most Arduinos SS pin is on D10, but there are also other models where it's different like D53 on Mega. Is there a way to know where it is? Like a global #define? I would like to avoid any pin configuration parameters in my library. At least for default configuration...


texts: How can i change by esp8266 baudrate, as I accidentally changed the baudrate to something else(which I dont remember)?

texts:
//In order to connect,

SoftwareSerial esp8266(2,3);

// the TX pin of esp8266 is connected to pin 3 of
// arduino uno and RX pin is connected to 2
// we need to pass baud rate to begin function

void setup()
{
  Serial.begin(115200);
  esp8266.begin(???); // what should i do in order to make it work?
}

What should i do in order to make it work?


texts: Sending arduino signal to another arduino

texts:
I'm working on a project which consists of 2 different function. since the arduino only can do 1 function so i decide to use 2 arduino instead. my idea is 1st arduino will give a output and the sketch on the 2nd arduino will run Only after the input given from the 1st arduino. So can i make a digital output which will be send to the input of 2nd arduino?

if it could be, i already make a code for the 2nd arduino which will be run after there was an input from the 1t arduino:

//define the input/output pins
#define FLOAT_SWITCH_PIN 2
#define PUMP_1_PIN 4
#define LED_PIN 7
#define output1starduino 3
//setup runs once
void setup()
{

  pinMode(FLOAT_SWITCH_PIN, INPUT_PULLUP);
  pinMode(output1starduino, INPUT_PULLUP);

  //setup output pins for relays/pumping station and LED board
  pinMode(PUMP_1_PIN, OUTPUT);
  pinMode(LED_PIN, OUTPUT);

}

//loop() runs indefinitely
void loop()
{

  if(digitalRead(output1starduino) == HIGH) // output from 1st arduino
  if(digitalRead(FLOAT_SWITCH_PIN) == LOW)
  {
     digitalWrite(PUMP_1_PIN, HIGH); //turn on the pump
     digitalWrite(LED_PIN, HIGH);    //turn on the LED
  }

  {
     digitalWrite(PUMP_1_PIN, LOW); //turn off the pump
     digitalWrite(LED_PIN, LOW);    //turn off the LED
  }
}

as i write on the line, the "output1starduino" which an digital output from the first arduino. Is this the right way for me to write if i want the program here to run only right after the output from 1st arduino given?

*** this is the code of first arduino which will be sent to the 2nd arduino

int motorPin = 3; // motor pengisian (m1)
int blinkPin = 4; //
int motor1 = 5;// motor pembuangan
int motorklorin = 6;// pam topap
int switch1 = 2;// switch float
int indicator1 = 7;
int indicator2 = 8;
int indicator3 = 9;
int output1starduino = 2;
void setup()
{
  pinMode(motorPin, OUTPUT);
  pinMode(blinkPin, OUTPUT); // penujuk fasa pengisian
  pinMode(motor1, OUTPUT);
  pinMode(motorklorin, OUTPUT); // MOTOR UNTUK topap
  pinMode(switch1, INPUT_PULLUP);// PELAMPONG
  pinMode(indicator1, OUTPUT);// lampu penunjuk fasa pembuangan
  pinMode(indicator2, OUTPUT);// lampu penunjuk topap
  pinMode(indicator3, OUTPUT);// lampu menunggu
  pinMode(output1starduino, OUTPUT); // KELUARAN KE ARDUINO 2
}

void loop()

{
  digitalWrite(motorPin, HIGH); // turn on the motor
  digitalWrite(blinkPin, HIGH); // turn on the LED
  digitalWrite(motor1, HIGH);// on lampu
  digitalWrite(motorklorin,HIGH);
  delay(1000);        //

  digitalWrite(motorPin, HIGH);  //
  digitalWrite(blinkPin, HIGH);  // penunjuk fasa pembuangan hidup
  digitalWrite(motor1, LOW);// motor pembuangan jalan (air start turun/pembuangan
  digitalWrite(motorklorin,HIGH);
  delay(180000);        //tempoh pembuangan

  digitalWrite(motorPin, LOW); // turn on the motor (motorisi balik air jalan/pengisian
  digitalWrite(blinkPin, LOW); //
  digitalWrite(motor1, HIGH);// filling motor on
  digitalWrite(indicator1, HIGH); //indicator
  delay(150000);        // duration filling

  digitalWrite(motorPin, HIGH);  // turn off the motor
  digitalWrite(blinkPin,HIGH);  // turn off the LED
  digitalWrite(motor1, HIGH);//
  digitalWrite(output1starduino, HIGH);
  delay(100000);        // multiply by 60000 to translate minutes to milliseconds
  }


texts: Arduino can't find my custom library: fatal error, Motor.h not found etc

texts:
I have been working on a project building a robot and using my own custom-built libraries to control it. However after converting all my old code into libraries Arduino can't find them.

Everything thing I have seen says to save them in the 'libraries' folder in with the sketches in MyDocuments and to reboot the Arduino Environment so it will recognize them.

Did that.

It even recognizes them in the sketch menu as libraries that can be imported. However, when I click on them to be included, a new blank line is entered into the sketch instead of an include statement. Perhaps this is some clue? I am really out of ideas at this point as to what I have done wrong.


texts: How to create an inverted PWM on the Due via software

texts:
Hello I am i need of a piece of code that lets me invert a PWM signal of two PWM pins on the due. Example D1 will be 101010 and D2 will be 010101. Is it possible?

Im pretty limited in my options because, doing it externally is not an option because there will be a time where a change in mode is needed and both pins will be sending signal independently. Manually pulling the pins High and Low is also not an option for me because this will make the code blocking other codes.


texts: Simulate motor encoder quadrature signals using an Arduino UNO

texts:
I'm supposed to write a raspberry pi and arduino code to read the RPM of a motor with an encoder attached to it. However, I'm having weird numbers and I'm unsure about the specs on the motor and the encoder. So I thought it would be smart to use a second arduino to simulate the motor with encoder.
The simulator would need to produce a 2 signals representing the two signals from the encoder. I want to be able to set the frequency and phase shift of these signals in software to imitate changes in speed and direction of the motor rotation. Forward would have one signal 90 degrees ahead, and then reverse having that same signal to be 90 degrees behind. So phase difference of plus or minus 90 degrees.
I'd like to eventually have the simulator be able to simulate motor actions like oscillating between forward and reverse 5 seconds each, or forward for 5 seconds and then stop completely.
I found this code by bigjosh which is more or less what I want to do. However, that code doesn't allow for a shift of -90 deg by default. I know there's a comment there to change it, but I'm not knowledgeable enough to understand what's going on exactly. I'd like someone to help me with that.


texts: Timer2 "Clear OC2B on Compare Match" not working as expected in CTC mode

texts:
This is a follow up to my previous question.

I have Timer2 in CTC mode, with TOP=OCR2A set to 150 (with a prescaler of 8, giving a 75us timing interval).

The datasheet states that setting COM2B1 to 1 in TCCR2A will "clear OC2B on compare match" (= Arduino pin D3) when you are in CTC mode.

I would like to use this functionality to get a "pwm" signal with a period of 75us, with duty cycle determined by OCR2B. I realize that this is a very convoluted way of achieving this, but eventually I want to be continually be changing OCR2B to get a (rapidly) varying duty cycle.

In the compare channel A interrupt I would like to turn D3 high, relying on the "clear on compare match" feature of channel B to turn it low a small interval later.

I have the following minimal(-ish) example:

#define OCIEA 1
#define CA21 1

void setup() {
  // PD3 as output
  DDRD |= (1 << PD3);

  // Pause the timers so they sync up
  GTCCR = (1<<TSM)|(1<<PSRASY)|(1<<PSRSYNC); // Halt all timers

  // Reset timer
  TCNT2 = 0; // set timer2 to 0 (8-bit timer)

  // Enable CTC mode
  TCCR2A = (1 << WGM21); // Timer 2 in CTC (TOP = OCR2A)

  // Clear output pins on compare match
  TCCR2A |= (1 << COM2B1); // Clear OC2B on match

  // Set prescaler
  TCCR2B = (1 << CA21); // set timer 2 divisor to 8

  // Set output compare
  OCR2A = 150; // Determines TOP for Timer2

  // Determines the pulse width
  OCR2B = 75; // Timer 2 output B (controls OC2B = PD3 = D3)

  // Enable interrupts for timer 2
  TIMSK2 = (1 << OCIEA);

  // Set the timers going again
  GTCCR = 0; // release all timers
}

ISR(TIMER2_COMPA_vect)
{
  TCCR2A &= ~((1 << COM2B1) | (1 << COM2B0)); // Disable clear OC2B on match
  DDRD |= (1 << PD3); // Enable output
  PORTD |= (1 << PD3); // Output high
  TCCR2A |= (1 << COM2B1); // Enable clear OC2B on match
}

void loop() {

}

Ideally the ISR would just consist of PORTD |= (1 << PD3); but this does not give my desired 50% duty cycle, but apparently it's impossible to write to the pin with COM2B1 enabled, so I tried various combinations of disabling it and reconnecting the pin but all I am getting is a very, very short pulse. It looks like as soon as COM2B1 is re-enabled, the pin goes low, even though a compare match on channel B should not have happened yet.

Setting COM2B0 instead of COM2B1 works as expected: the pin toggles state (but this is not what I want).

Why does this not work the way I expect it to, and is there a way to get my desired behavior? Also, if this is not possible, what on earth is the purpose of the clear on compare match feature if you can't turn the pin on at all when using it?

I have discovered I can sort of get the behavior I want by setting COM2B0 instead of COM2B1 (toggle on match rather than clear on match) and forcing a compare match in the interrupt (toggling the pin off) so that later the "real" toggle on match will turn it off. However, this is not ideal (as if the real and forced match overlap, I would lose track of the pin's state), and I'm still wondering what the purpose of the clear on match functionality is if it just forces the pin low.


texts: How do I change the default number of parameters SDI 12?

texts:
I am a nooby so this might be an obvious answer kind of a question, but how do I change how many parameters arduino-uno reads from a sensor using SDI communication? My code (which was in public domain, an example for SDI communication) has no problems taking 3 or less parameters but the probe I have has 7 sensors in it and I need all of their values (but all I get in return is 1, literally just the number 1). If I remove and leave only 3 sensors in the probe it works normally. So the problem is not in the communication but in the quantity of data. My code:

    #include <SDISerial.h>
    #define DATALINE_PIN 2
    #define INVERTED 1

    SDISerial sdi_serial_connection(DATALINE_PIN, INVERTED);

    char* get_measurement(){
     char* service_request = sdi_serial_connection.sdi_query("?M!",60000UL);
     char* service_request_complete = sdi_serial_connection.wait_for_response(900);
     return sdi_serial_connection.sdi_query("?D0!",60000UL);
    }

    void setup(){
     sdi_serial_connection.begin(); // start our SDI connection
     Serial.begin(9600); // start the connection
     Serial.println("OK INITIALIZED"); // startup string
     delay(90000); // startup delay to allow sensor to powerup, 1.5 min
    }

    void loop(){
     char* response = get_measurement(); // get measurement data

     if (response!=NULL && response[0] != '\0')
      Serial.println(response);
     else
      Serial.println("No Response");
     delay(1500);
    }


texts: How to change this function in to a non-blocking function?

texts:
How do I modify the getTheNumber() function to satisfy the statement below??
"
This function blocks until the user is done typing the number. Try to rewrite it in a non-blocking fashion. For example, it could return -1 on every call as long as the user is not done typing the number. On the first call after the user is done it would return the valid value. If you manage to write everything non-blocking, then you loop() will restart very often, and the program will work with no significant latency."

Here is the code:

int getTheNumber()
{
    char buffer[4];
    // Input up to 3 numbers until we find a * or #
    int i=0;
    while (1)
    {
        char key = keypad.getKey();

        // If it's a number AND we have space left, add to our string
        if ('0' <= key && key <= '9' && i < 3)
        {
            buffer[i] = key;
            i++;
        }
        // If it's a * or #, end
        else if ('#' == key && i > 0)
        {
            // Null terminate
            buffer[i] =0;
            int value = atoi(buffer);
            break;
        }
    }
    return atoi(buffer);
    }


texts: How to get ip information of arouter/AP with ESP8266

texts: i, I would like to get ip number, DHCP ip range subnet mask information of an external AP/router autonomusly through the ESP8266 sketch, so the ESP8266 code can determine a suitable static ip range to configure. Any example code or references would be appreciated.


texts: How to interface an arduino to load sensor with darlington transistor?

texts:
I have a load sensor for measuring weights , it has for wires labelled E+,E-,S+,S-. I assume S means sensor and E means excitation and the power is sent into E+ and E-.
The output of any load sensor would be the order of typically millivolts if it takes a load (depending on the weight of the load of course) so I guess amplifying it with a darlington would make its output useful for an interface to an arduino.
What would be a generic circuit using a darlington transistor (e.g. a TIP 120) that can make the load sensor output useful for building an interface to an arduino with the minimal number of components? Ans this circuit is to be as simple as possible.
Im trying to build a circuit with the components I have which does include a tip 120 and I have a lot of other common components.


texts: confirming this will blink LED at given frequency

texts:
I want to blink an LED at an specific frequency, ie: 7Hz
here what Im doing
int ledPin = 4;
float freq = 7;

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

float periodo() {
  float peri = 1/freq;
  float halfer = peri/2;
  float millisec = halfer*1000;
  return millisec;
  //return ((1/freq)/2)*1000;
}

void loop() {
  digitalWrite(ledPin, HIGH);
  delay(periodo());
  digitalWrite(ledPin, LOW);
  delay(periodo());
}

Is this correct? is that the best way to do it?
thanks in advance!


texts: Do I need an external power supply for the SG90 micro servo?

texts:
I have a Uno R3 and although I can add an external power supply for the SG90 micro servo it would make the project more complicated. Can I power the servo using the 5v pin of the Uno R3?

I measured the current and it does not seem to pass 160mA and in normal use, it uses only 60mA.


texts: ESP8266 stops responding when isolated relay is connected to AC tubelight

texts:
I'm completely new to Arduino and do not have an electronics background.
I'm really keen to do a POC on home automation. As a start, I decided to switch on a tube light using ESP8266, Arduino Uno R3 and isolated relay. I have read that this can be done without arduino also.
I'm able to switch on and switch off the relay without any problem. But when the relay is connected to the tube light, the ESP8266 stops responding. I couldn't find what was causing the issue.
I also read that the ESP2866 should be powered properly to function correctly. I'm following the wiring schema 5 mentioned in the link http://yaab-arduino.blogspot.in/2015/03/esp8266-wiring-schemas.html.

This is my code.
#include <SoftwareSerial.h>

#define DEBUG true
int relay = 8;
SoftwareSerial esp8266(2, 3); // make RX Arduino line is pin 2, make TX Arduino line is pin 3.
// This means that you need to connect the TX line from the esp to the Arduino's pin 2
// and the RX line from the esp to the Arduino's pin 3
void setup()
{
  Serial.begin(9600);
  esp8266.begin(115200); // your esp's baud rate might be different
  pinMode(relay, OUTPUT);
  digitalWrite(relay, LOW);

  sendData("AT+RST\r\n", 2000, DEBUG); // reset module
  sendData("AT+CWMODE=3\r\n", 1000, DEBUG); // configure as access point
  sendData("AT+CWJAP=\"xxxx\",\"xxx\"\r\n", 5000, DEBUG); // configure as access point

  sendData("AT+CIPMUX=1\r\n", 1000, DEBUG); // configure for multiple connections
  sendData("AT+CIPSERVER=1,80\r\n", 1000, DEBUG); // turn on server on port 80
  sendData("AT+CIFSR\r\n", 5000, DEBUG); // get ip address
  sendData("AT+CIFSR\r\n", 5000, DEBUG); // get ip address
}

void loop()
{
  if (esp8266.available()) // check if the esp is sending a message
  {

    if (esp8266.find("+IPD,"))
    {
      delay(1000);

      int connectionId = esp8266.read() - 48; // subtract 48 because the read() function returns
      // the ASCII decimal value and 0 (the first decimal number) starts at 48

      if (esp8266.find("=="))
      {
        Serial.print("State : ");
        char c = esp8266.read();
        Serial.print(c);
        if (c == '1') {
          digitalWrite(relay, HIGH);
        }
        else {
          digitalWrite(relay, LOW);
        }
      }
      String webpage = "A";

      String cipSend = "AT+CIPSEND=";
      cipSend += connectionId;
      cipSend += ",";
      cipSend += webpage.length();
      cipSend += "\r\n";

      sendData(cipSend, 1000, DEBUG);
      sendData(webpage, 1000, DEBUG);

      String closeCommand = "AT+CIPCLOSE=";
      closeCommand += connectionId; // append connection id
      closeCommand += "\r\n";

      sendData(closeCommand, 3000, DEBUG);
    }
  }
}

String sendData(String command, const int timeout, boolean debug)
{
  String response = "";

  esp8266.print(command); // send the read character to the esp8266

  long int time = millis();

  while ( (time + timeout) > millis())
  {
    while (esp8266.available())
    {

      // The esp has data so display its output to the serial window
      char c = esp8266.read(); // read the next character.
      response += c;
    }
  }

  if (debug)
  {
    Serial.print(response);
  }

  return response;
}

The above code works perfectly until I connect the tube light to the relay.
The power supply used in 9v 1A wall adapter.
The relay used is http://www.amazon.in/gp/product/B00LL0M6RS?psc=1&redirect=true&ref_=oh_aui_detailpage_o03_s00.
The v+ of the relay is connected directly to the wall adapters voltage and ground to ground of wall adapter. The input of the relay is connected to Arduino digital pin 8.
I'm really struggling hard to proceed here. Any help or hint would be much appreciated.
Thanks in advance.


texts:
I have written a simple code to read data from capacitive keypad and display it on LCD.

I am getting the data from keypad in following data structure.

char phoneNumber[PHONE_DIGITS];

and then displaying the data on LCD as

   LcdString(phoneNumber[i]);

where my LCD string function is

void LcdString(char *characters)
{
  while (*characters)
  {
    LcdCharacter(*characters++);
  }
}

There is a type cast error

  error: invalid conversion from 'char' to 'char*' [-fpermissive]

How can I debug it?


texts: Run multiple function with different argument/return structure by one function pointer

texts:
Edit:
I tried a simple code in Arduino IDE which should've done in the first place instead in doing it in a desktop compiler. Because the results are different by experiment. In the desktop C compiler, it's working and bypassing the code without much problems, just one or two warnings.
But in Arduino IDE, it's not acceptable and gives error.
This is the code:
// functions
void function1(uint8_t x, uint8_t y){
  int z = x + y;
  Serial.println("function1\n");
  Serial.println(z);
}
uint8_t function2(uint8_t x, uint8_t y){
    Serial.println("function2\n");
    return 1;
}

void (*fun_ptr)();

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

  Serial.begin(9600);
  fun_ptr = (void (*)())function2;
  int value;

  value = fun_ptr(1,2);

}

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

}


texts: I would like to control 16 motors with a servo shield

texts:
Ok so I've used nicks code and have the code running once ok.... I the noticed however I had a fast 180 sweep and then it returned under control of code. I then noticed the comments wrt pulselen of 1000 being zero degrees and using 1500 as 90 degrees.... Wow so I get a single movement which holds but it doesn't go 90 degrees...

I'm using an Adafruit servo shield.

I can make my servo move. However, I want to stop it at 90 degrees without it returning to 0 degrees each time.

What am I missing?

The code I've used is as follows:

void setup()
{
  pwm.begin();
  pwm.setPWMFreq(60);  // Analog servos run at ~60 Hz updates
}

void loop()
{
  for (uint16_t pulselen = SERVOMIN; pulselen < SERVOMAX; pulselen++)
  {
    pwm.setPWM(0, 0, pulselen);
  }
  delay(500);
}


texts: Why my light meter's values are blank on Arduino Serial Monitor?

texts:
I tried to represent the values of TSL 2591 Adafruit light sensor on my Arduino Serial Monitor, but for some reason, I could not do that. The Arduino Serial Monitor just enters some blank values and scrolls down.
Here is the code:

uint16_t x = tsl.getLuminosity(TSL2591_VISIBLE);
y = float(tsl.getLuminosity(TSL2591_VISIBLE));
z = (y, DEC);
Serial.write((byte)z);

x, y, and z are floats initially.


texts:
I'm trying to use 3 pins as capacitive pins along side the Mozzi.

I had several attempts and so far the closest I had was using code from the ADCTouch library straight into the main code, but with the current implementation (removing averaging and taking less samples to speed things up) it's only fast enough to process 1 pin and I'd like to use 3.

Here is my implementation so far:

/*  Based on the Gain Example changing the gain of a sinewave,
    using Mozzi sonification library.

    Demonstrates the use of a control variable to influence an
    audio signal.

    Circuit: Audio output on digital pin 9 on a Uno or similar, or
    DAC/A14 on Teensy 3.0/3.1, or
    check the README or http://sensorium.github.com/Mozzi/

    Mozzi help/discussion/announcements:
    https://groups.google.com/forum/#!forum/mozzi-users

    Tim Barrass 2012, CC by-nc-sa.
*/

#include <MozziGuts.h>
#include <Oscil.h> // oscillator template
#include <tables/sin2048_int8.h> // sine table for oscillator

// use: Oscil <table_size, update_rate> oscilName (wavetable), look in .h file of table #included above
Oscil <SIN2048_NUM_CELLS, AUDIO_RATE> aSin(SIN2048_DATA);

// control variable, use the smallest data size you can for anything used in audio
byte gain = 255;

//ADC Touch setup
int sampleCount[3] = {0};
int values[3] = {0};

void setup(){
  startMozzi(); // start with default control rate of 64
  aSin.setFreq(4200); // set the frequency
}

void updateControl(){
  if(gain > 3){
    gain = gain - 3 ;
  }else{
    gain = 0;
  }
  //begin ADCTouch
  pinMode(A4, INPUT_PULLUP);

  ADMUX |=   0b11111;
  ADCSRA |= (1<<ADSC); //start conversion
  ADCSRA |= (1<<ADIF); //reset the flag

  pinMode(A4, INPUT);

  values[0] = mozziAnalogRead(A4);
  sampleCount[0]++;
  //end ADCTouch

  if(sampleCount[0] == 64){//wait for 64 samples
    if(values[0] > 500) {//did we get a touch with all these samples ?
      gain = 255;//amp it up
    }
    sampleCount[0] = 0;//reset count
  }

}

int updateAudio(){
  return (aSin.next()* gain)>>8; // shift back to STANDARD audio range, like /256 but faster
}

void loop(){
  audioHook(); // required here
}

The issue is as soon as do the pinMode calls for the second pin I'd like to use (A5) so I'm guessing pinMode needs to work faster. To use pinMode(INPUT_PULLUP) and pinMode(INPUT) calls for pins A4,A5 and digital 10, now can I write this using direct port manipulation ?

(I'm new to avr/arduino internals and slowly getting the grips with this).


texts:
I need to use atmega328P without arduino board, so far I know that I will need 16MHZ Quartz Resonator and two 22nf capacitors. However, I have seen that other people are using atmega328P without capacitors.

What is the role of those capacitors? Can I use atmega328P without capacitors?


texts: ESP-01 Deep Sleep not waking up properly

texts:
I have a temperature/humidity project using an ESP-01 and DHT11.  I want to be able to put t into deep sleep to preserve battery life.  I have soldered a wire from GPIO16 to RST.

#include <SimpleTimer.h>  //https://github.com/jfturcot/SimpleTimer
#include <ESP8266WiFi.h>
#include <PubSubClient.h>  //https://github.com/knolleary/pubsubclient
#include <ESP8266mDNS.h>
#include <WiFiUdp.h>
#include <ArduinoOTA.h>  //https://github.com/esp8266/Arduino/tree/master/libraries/ArduinoOTA
#include "DHT.h"

//USER CONFIGURED SECTION START//
#define DHTPIN 2     // what digital pin we're connected to

const char* ssid = "mySSID";
const char* password = "password";
const char* mqtt_server = "mqttserverip";
const int mqtt_port = 1883;
const char *mqtt_user = "usser";
const char *mqtt_pass = "pass";
const char *mqtt_client_name = "DryerMCU"; // Client connections can't have the same connection name
//USER CONFIGURED SECTION END//

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

// Initialize DHT sensor.
// Note that older versions of this library took an optional third parameter to
// tweak the timings for faster processors.  This parameter is no longer needed
// as the current DHT reading algorithm adjusts itself to work on faster procs.
DHT dht(DHTPIN, DHTTYPE);

WiFiClient espClient;
PubSubClient client(espClient);
SimpleTimer timer;

bool boot = true;
int status = WL_IDLE_STATUS;

//Functions
void setup_wifi()
{
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(ssid);
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED)
  {
    delay(500);
    Serial.print(".");
  }
  Serial.println("");
  Serial.println("WiFi connected");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());
}

void getTemperature()
{
  // Reading temperature or humidity takes about 250 milliseconds!
  // Sensor readings may also be up to 2 seconds 'old' (its a very slow sensor)
  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");

  char temperature[50];
  char humidity[50];

   // Update temperature and humidity
  String temp_str = String(f);
  temp_str.toCharArray(temperature, temp_str.length() + 1);
  client.publish("dryer/temperature", temperature);

  String hum_str = String(h);
  hum_str.toCharArray(humidity, hum_str.length() + 1);
  client.publish("dryer/humidity", humidity);

}

void setup() {
  Serial.begin(38400);
  delay(2000);
  Serial.println("Booting");

  dht.begin();
  setup_wifi();
  client.setServer(mqtt_server, mqtt_port);
  getTemperature();

  Serial.println("Going to sleep");
  ESP.deepSleep(10000000,RF_DEFAULT);
}

void loop() {

}

When I start it up it takes one measurement, goes to sleep and then wakes up, but nothing happens once it wakes up.  Serial output:

Booting

Connecting to SSID
  ......
WiFi connected
IP address:
mqttip
Humidity: 51.00 %   Temperature: 20.00 *C 68.00 *F  Heat index: 19.39 *C 66.90 *F
Going to sleep

ets Jan  8 2013,rst cause:5, boot mode:(3,7)

ets_main.c


texts: Moving and Stopping Stepping motor without using delay

texts:
I'm using a stepper motor with an external limit switch (so when power is on the motor will know where to start from) with an L6470 motor drive.
What I want to do here is

when power is ON → turn Clock Wise (CW) until it hits external Limit Switch
Once the limit switch is ON → Turn Anti-Clock Wise (CCW) for 550 mil seconds
Rest for 100 mil seconds
Turn Clock Wise (CW) for 200 mil seconds
Rest for 100 mil seconds
Turn Anti-Clock Wise (CCW) for 200 mil seconds
....loop from 3 to 6

My current code is using "counter". This is because I can't use "delay" in this code since it interrupts the limit switch activation code.
I've only written easy codes and don't know how to make it rest without using "delay".
Please help....
/***********************

回転

************************/
#include <Arduino.h>
#include <SPI.h>

/*************

long max_speed = 7000;// 70000 固定

long int dd = 200;// 微増・微減の量 400
int dt = 10; // 微増・微減にかける時間　ミリ秒

int t_interval = 10;// (休止する時間 みり秒）
int t_hold = 170; //　最高速を維持する時間　ミリ秒）

int steps;

#define PIN_SPI_MOSI 11
#define PIN_SPI_MISO 12
#define PIN_SPI_SCK 13
#define PIN_SPI_SS 10

#define PIN_L6470_SS PIN_SPI_SS

void L6470_write(unsigned char data);
void L6470_init(void);
void L6470_run(long speed);

long speed = 1000;
long int n_dir = 0 ;
long offTime;

int c_step = max_speed / dd;

const int limit_sw = 7;
bool switchState = false;
int counter = 0;
int milsec = 0;
bool speedSwitch = false;

void setup()
{
 pinMode(PIN_SPI_MOSI, OUTPUT);
 pinMode(PIN_SPI_MISO, INPUT);
 pinMode(PIN_SPI_SCK, OUTPUT);
 pinMode(PIN_L6470_SS, OUTPUT);

 pinMode(limit_sw, INPUT_PULLUP );

 digitalWrite(PIN_L6470_SS, HIGH);

 SPI.begin();

 Serial.begin(9600);

 L6470_init();

 Serial.println("Start...");

void loop()
{

int value = digitalRead(limit_sw);

if(value == 0){
  counter ++;
  if(counter > 50){//もともと３
    switchState = true;
    counter = 50;
  }
}
if (switchState == true){
  milsec++;
  Serial.println(milsec);
  if(milsec > 550){
    speedSwitch = !speedSwitch;
    milsec = 0;
  }

  int speed;
  if(speedSwitch == true){
    //Serial.println("speedSwitch : true");
    speed = 200;

  }

  else{
    //Serial.println("speedSwitch : false");
    speed = -200;
  }

}

else{

   L6470_run( 100 );//速度

}
}

void L6470_write(unsigned char data)
{
 // ~SSイネーブル。
 digitalWrite(PIN_L6470_SS, LOW);
 // SPI転送。
 SPI.transfer(data);
 // ~SSディスエーブル。
 digitalWrite(PIN_L6470_SS, HIGH);
}

void L6470_init()
{
 // MAX_SPEED設定。
 /// レジスタアドレス。
 L6470_write(0x07);
 // 最大回転スピード値(10bit)　００２０

 L6470_write(0x00);
 L6470_write(0x90);

 // KVAL_HOLD設定。
 /// レジスタアドレス。
 L6470_write(0x09);
 // モータ停止中の電圧設定(8bit)
 L6470_write(0xFF);

 // KVAL_RUN設定。
 /// レジスタアドレス。
 L6470_write(0x0A);
 // モータ定速回転中の電圧設定(8bit)
 //L6470_write(0xFF);
 L6470_write(0x64);

 // KVAL_ACC設定。
 /// レジスタアドレス。
 L6470_write(0x0B);
 // モータ加速中の電圧設定(8bit)
 L6470_write(0xFF);

 // KVAL_DEC設定。
 /// レジスタアドレス。
 L6470_write(0x0C);
 // モータ減速中の電圧設定(8bit)
 L6470_write(0xFF);

 // OCD_TH設定。
 /// レジスタアドレス。
 L6470_write(0x13);
 // オーバーカレントスレッショルド設定(4bit)
 L6470_write(0x0F);

 // STALL_TH設定。
 /// レジスタアドレス。
 L6470_write(0x14);
 // ストール電流スレッショルド設定(4bit)
 L6470_write(0x7F);
}

void L6470_run(long speed)
{
 unsigned short dir;
 unsigned long spd;
 unsigned char spd_h;
 unsigned char spd_m;
 unsigned char spd_l;

//spd = speed;

 // 方向検出。

 if (speed < 0)
 {
  dir = 0x50;
  spd = -1 * speed;
 }
 else
 {
  dir = 0x51;
  spd = speed;
 }

 // 送信バイトデータ生成。
 spd_h = (unsigned char)((0x0F0000 & spd) >> 16);
 spd_m = (unsigned char)((0x00FF00 & spd) >> 8);
 spd_l = (unsigned char)(0x00FF & spd);

 // コマンド（レジスタアドレス）送信。
 L6470_write(dir);
 // データ送信。
 L6470_write(spd_h);
 L6470_write(spd_m);
 L6470_write(spd_l);

  Serial.print( " current spd = ");
  Serial.println( spd );
}


texts:
I've got a project in which I'll be controlling 8 24V/10A brushless DC motors with an Arduino Due on a quadrupedal robot. I've been having trouble finding ESCs that would work well for this application and was wondering if anyone could provide recommendations. My ideal ESC would be one with on-board PID control given an encoder. In looking around, I've only been able to find one ESC with this capability but lacked the power output these motors want.
A secondary question would be if it's reasonable to run 8 PID loops on the Due alongside its other tasks (primarily serial data receiving/transmitting). I feel like it might be too much for the Due to handle, but I wanted to get other's opinions on this.
Sidenote: I have enough of a gear reduction between motor and output shaft that fine movements should not be an issue.


texts: How to use Atmega328p-PU from an Uno, on a breadboard without a crystal

texts: How do you use Atmega328p-PU from an Uno, on a breadboard without a crystal?


texts:
Good night! Based on stuff I get a bit here and there, came up with a program for an Arduino Audio Selector with shift registers and some features. Working as expected, only missing connecting the relay boads, but that's for future. Since I have a few devices, instead of having to write all, is there anyway of I change for instance a line and then on display show that line?

Thanks. Here's my code, realy big, try to short the part of the shift registers but seems to me it was unstable.

Arduino selector 4x20


texts:
Is there a definitive list of which Arduino architectures support the ATOMIC_BLOCK() macro, and a list of #defines for each architecture?
I've tried searching through the Arduino cores on GitHub to see where ATOMIC_BLOCK is used. If it's not used in a core, I've assumed it's not supported. I generated this list based upon that assumption, but how accurate is it?
ArduinoCore         Supported       Archived    #define
-------------------------------------------------------
  samd
  avr                  Yes                      __AVR__
  arc32
  sam                  Yes
  primo                               Yes
  megaavr              Yes
  API
  nRF528x-mbedos
  mbed

I would like to write some code, something like this (edited in response to comments):
#define ATOMIC_BLOCK_SUPPORTED (__AVR__ || __MEGAAVR__ || __SAM__)
.
.
.
#if ATOMIC_BLOCK_SUPPORTED
    ATOMIC_BLOCK(ATOMIC_RESTORESTATE)
    {
#endif

        // Do not disturb.

#if ATOMIC_BLOCK_SUPPORTED
    }
#endif

For architectures that don't support ATOMIC_BLOCK, I would like to write my own code to save, disable and restore the global interrupt flag, something like this.
    asm
    {
        // Save interrupt flag.
    }
    // Clear interrupt flag.
    // Do not disturb.
    // Restore interrupt flag.

Potential Solution?
#ifdef __AVR__
#include <util/atomic.h>
#elif defined(__ARCH2__)
#define ATOMIC_BLOCK(/* for architecture 2 */)
#elif defined(__ARCH3__)
#define ATOMIC_BLOCK(/* for architecture 3 */)
// etc
#endif
.
.
.
#ifdef ATOMIC_BLOCK
    ATOMIC_BLOCK(ATOMIC_RESTORESTATE)
    {
#endif

        // Do not disturb.

#ifdef ATOMIC_BLOCK
    }
#endif

Is there a definitive list of code that saves, disables and restores the global interrupt flag for every Arduino architecture that could be dropped into each #elif branch?


texts: What do the charactors " '/2' " mean in the variable declaration?

texts:
I'm working on an RS485 project, In the CPP file there are const variables declared in the following manner:

#include <RS485_protocol.h>
const byte STX = '\2';
const byte ETX = '\3';

What does the '\2' and '\3' mean?


texts:
In my code I have that string:String code = rs1 + rs2 + rs3; //rs1=034, rs2=000, rs3=017 It means that code = "034000017". But if I run if (code.equals("034000017")) Serial.println("OK"); There is nothing in serial monitor. Here is full code:

String code, rs1, rs2, rs3, readString;
void setup() {
    Serial.begin(9600);
    Serial.println("Serial ready!");
}

void loop() {
    if (Serial.available()) {
        while (Serial.available()) {
          delay(10);
          if (Serial.available() >0) {
            char c = Serial.read();
            readString += c;
            rs1 = readString.substring(0, 3); //034
            rs2 = readString.substring(3, 6); //000
            rs3 = readString.substring(6, 9); //017
            code = rs1 + rs2 + rs3;
            Serial.println(code);
            if (code.equals("034000017")) Serial.println("OK");
          }
        }
    }
}


texts:
I'm developing a arduino based system, which includes a alarm system.

Searching on the Internet, I found these lybraries "Time.h" and "TimeAlarms.h".

In the requirements, it says: "Time does not require any special hardware. Internally, Time depends upon Arduino's millis() function to keep track to elasped time."

Considering Arduino's millis() rollover after 49.7 days, how can I ensure these lybraries are handling the rollover well?

I don't think that waiting 49.7 days to test it is the better way.


texts: Classes and objects: how many and which file types do I actually need to use them?

texts:
I have no previous experience with C++ or C, but know how to program C# and am learning Arduino. I just want to organize my sketches and am quite comfortable with the Arduino language even with its limitations, but I really would like to have an object-oriented approach to my Arduino programming.

So I have seen that you can have the following ways (not exhaustive list) to organize code:

A single .ino file;
Multiple .ino files in the same folder (what the IDE calls and displays like "tabs");
An .ino file with an included .h and .cpp file in the same folder;
Same as above, but the files are an installed library inside Arduino program folder.

I have also heard of the following ways, but have not got them working yet:

Declaring a C++-style class in the same, single .ino file (have heard of, but never seen working - is that even possible?);
[preferred approach] Including a .cpp file where a class is declared, but without using a .h file (would like this approach, should that work?);

Note that I only want to use classes so that code is more partitioned, my applications should be very simple, only involving buttons, leds and buzzers mostly.


texts:
I'm using a ItsyBitsy 32u4, Adafruit says it can act as a USB HID keyboard. The mc is based on the 32u4 which the Keyboard docs say are supported.

I have a simple sketch that prints "A" every second and should press "A". When I upload the sketch and connect to the serial port I see the print output but I don't get any key presses.

Any ideas? I'm on linux, I suspect that the controller doesn't register as a HID device, maybe I need UDEV rules or drivers?

EDIT: the keyboard works on a different computer.

#include <Keyboard.h>
void setup() {
  Serial.begin(9600);
  Keyboard.begin();
  Serial.println("Start");
}

void loop() {
  Serial.println("a");
  Keyboard.write('a');
  delay(1000);
}


texts: Arduino-like boards with other microcontrollers

texts: Are there any Arduino-like board designs that are NOT using an AVR chip, but perhaps a chip like the Z80 or the 6502?


texts:
I want to know why Wire.onRequest can not detect below massage and what I can do to detect it.(I am not able to change I2C massage)

I was able to read this part of the massage with wire.onReceive:

But I can not read this massage at all, which is requesting:

#include <Wire.h>
byte val = 170;
int sendv;

char c;

byte dataArray[16];

void setup() {
  Wire.begin(0x77);                // join i2c bus with address #8
  Wire.onReceive(receiveEvent); // register event
  Wire.onRequest(requestEvent); // register event
  Serial.begin(9600);           // start serial for output
}

void loop() { }

void receiveEvent(int howMany) {
  Serial.println(howMany);

  if (howMany >= 2) {
    for (int i = 0 ; i < howMany; i++) {
      dataArray[i] =  Wire.read();
      Serial.println(dataArray[i], HEX);
    }

  } else {
    c =  Wire.read();
    Serial.println(c, HEX);
  }
}

void requestEvent() {
  Serial.println("REqEVENT");
}


texts: Initialization of function pointer array

texts:
I have an array of function pointers:

unsigned int dimension = 8;
void (* myFunctions [dimension])();

This array is a member of a class:

class myClass {

    static const unsigned int dimension;

    void (* myFunctions [dimension])();
}

and in a cpp file:

const unsigned int dimension = 8;

It's size is known at compile time, but it's values will be added through a public method in unknown parts of the code. I need to be able to find out at any time whether there is a valid pointer at some index in that array at any time, and my idea was to do that by comparing the pointer against nullptr: if it doesn't equals it then I'll assume that it holds a valid function pointer.

I was wondering if I need to initialize the array before making that kind of speculation. How is this array initialized if I only write the above two lines of code? Can I assume something like myFunctions[x] ==  nullptr is true in that case? Or do I need to do an explicit initialization like the following one?

for(int i = 0; i < dimension; i++)
    myFunctions[i] = nullptr;


texts: what is causing my esp8266 setup function to reinitialise?

texts:
Here is code I have written:

#include <stdio.h>
#include <ESP8266WebServer.h>

#define MAX_WIFI_INIT_RETRY 50
#define WIFI_RETRY_DELAY 500

const char* wifi_ssid = "ssid";
const char* wifi_passwd = "password";

ESP8266WebServer http_rest_server(80);

const int numParams = 20;
String params [numParams];

String toString(String my_array[], int size)
{
  String string;
  for (int i = 0; i < size; i++) {
    string = string + ", " + my_array[i];
  }
  return string;
}

int init_wifi() {
  int retries = 0;
  Serial.println("Connecting to WiFi AP..........");
  WiFi.mode(WIFI_STA);
  WiFi.begin(wifi_ssid, wifi_passwd);
  // check the status of WiFi connection to be WL_CONNECTED
  while ((WiFi.status() != WL_CONNECTED) && (retries < MAX_WIFI_INIT_RETRY)) {
    retries++;
    delay(WIFI_RETRY_DELAY);
    Serial.print("#");
  }
  return WiFi.status(); // return the WiFi connection status
}

void readParams(String (& params) [numParams])
{
  int mn = WiFi.scanNetworks();
  for (int i = 0; i < mn; i++)
  {
    //    Serial.println(WiFi.SSID(i).c_str()); // prints name of all hotspots in serial monitor.
    params [i] = WiFi.SSID(i).c_str();
  }
}

void listHotspots() {
  String results = toString(params, sizeof(params));
  Serial.println(results);
  http_rest_server.send(200, "text/plain", results);
}

void config_rest_server_routing() {
  http_rest_server.on("/", HTTP_GET, []() {
    http_rest_server.send(200, "text/html",
                          "Welcome to the ESP8266 REST Web Server");
  });
  http_rest_server.on("/hotspots", HTTP_GET, listHotspots);
}

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

  init_led_resource();

  WiFi.mode(WIFI_STA);
  WiFi.disconnect();
  readParams (params);

  if (init_wifi() == WL_CONNECTED) {
    Serial.print("Connetted to ");
    Serial.print(wifi_ssid);
    Serial.print("--- IP: ");
    Serial.println(WiFi.localIP());
  }
  else {
    Serial.print("Error connecting to: ");
    Serial.println(wifi_ssid);
  }

  config_rest_server_routing();

  http_rest_server.begin();
  Serial.println("HTTP REST Server Started");
}

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

when I access the root url: i.e. 192.168.0.101/ It opens the root page fine, but when I try to open the 192.168.0.101/hotspots It reboots the ESP8266  until the page stops to make a new attempts and I get nothing in result.

In the serial monitor I am seeing this exception when I try to visit the ip/hotspot page .

Exception (9):
epc1=0x4020148a epc2=0x00000000 epc3=0x00000000 excvaddr=0x4d2d5456 depc=0x00000000

>>>stack>>>

ctx: cont
sp: 3ffffde0 end: 3fffffc0 offset: 01a0
3fffff80:  3fffdad0 3ffee553 3ffee5a4 40201347
3fffff90:  402086b8 6505a8c0 feefeffe feefeffe
3fffffa0:  3fffdad0 00000000 3ffee5e0 40206614
3fffffb0:  feefeffe feefeffe 3ffe8510 40100479
<<<stack<<<

 ets Jan  8 2013,rst cause:4, boot mode:(3,6)

wdt reset
load 0x4010f000, len 1384, room 16
tail 8
chksum 0x2d
csum 0x2d
v8b899c12
~ld
Connecting to WiFi AP..........
######Connetted to Hometelecom1N5E--- IP: 192.168.0.101
HTTP REST Server Started

is it something wrong with the toString function ?


texts: What pins can be used for chip select (CS, CC) on the Arduino nano every?

texts: I’ve checked the nano’s tech specs but I can’t seem to find any information regarding it. I’ve tried setting it to pin 26 (digital output)


texts:
I'm new to the Arduino world. The last time i was programming microprocessors, was back with the Z80 in assembly language.

I am also teaching myself C++ and seems to be going quite well.

I have decided to write my own 'library' for driving 7 segment LED's. The reason for writing my own, rather then using an existing one is to aid with the learning process. I'm quite pleased to say it works ( it may not be the most efficient code)

The books I have on C++ are great, but i do find sometimes the explanation of concepts seem to get lost.

what I would like to know, how do you go about initialising an object class in setup() and using it in loop()? I have this sneaky suspicion that it involves creating the object on the heap, and passing a pointer to the object over somehow.

I could just initialise it once in loop(), and make my own continuous loop afterwards, but there are other things done between the and of a loop() and the beginning of the next loop() (things like timer interrupts).

I will post the code im using, but not the library unless asked to, as it is quite a few lines.

# include "Leddisplay.h"
void setup() {

    byte Digit[9] = { 22, 23 , 24 ,25, 26, 27, 28, 29, 2 };

    Leddisplay *pRightDigit = new Leddisplay(Digit);

}

void loop() {

    pRightDigit->setDigit(5);
    pRightDigit->displayDigit();

}

^^  Obviously this does not compile  ^^

# include "Leddisplay.h"
void setup() {

}

void loop() {

    byte Digit[9] = { 22, 23 , 24 ,25, 26, 27, 28, 29, 2 };
    Leddisplay *pRightDigit = new Leddisplay(Digit);

    pRightDigit->setDigit(5);
    pRightDigit->displayDigit();

    for (;;);   // or do.. while within which has other code to repeat
                // but wont allow anything to be executed between loop() iterations

}

^^  This does, and runs fine, but may not achieve what I want  ^^

I'm not sure if I have used the right wording, or even asked the right question.
Thank you for any help in advance.
Dave


texts: Will avrdude overwrite the bootloader on my Nano?

texts:
I bought an arduino nano (knockoff from Elegoo) and according to the Amazon description it comes with a bootloader.

From what I've read, this means that programming can occur over the usb connection rather than having to rely on a dedicated serial programmer.

I installed the necessary drivers, plugged in the Nano, and ran this command (not to program, just to see if the board would be recognized):

avrdude -p m328p -b 57600 -P /dev/wcbhserial1460 -c arduino

It recognized the board and said it was ready to be programmed. If I then actually go ahead and ask it to flash a hex file onto the board, will the -c arduino argument tell avrdude to use the bootloader or does it just overwrite everything? Can I reprogram multiple times using this command?

I'm using Atmel Studio 7 and am configuring it to call the appropriate avrdude command.

EDIT: According to this answer, the -D flag will program the chip without clearing the flash, allowing the bootloader to preserved. Unfortunately, since the ATmega devices don't support partial flash memory clearing, this will only work once. So essentially I need to reupload the bootloader each time, which kinda defeats the purpose of it right?

It looks like though he is talking about using an AVRISP, so does all that not apply if you're just programming using the bootloader and the usb connection in the first place?


texts: Analog inputs showing value even there is nothing connected to it

texts:
After watching something weird on the serial monitor I wrote a simple code to monitor the analog pin input values. There was nothing connected to the analog pins still they where showing decimal representation of some analog values.

the code is

float ana [] = {A0,A1,A2,A3,A4,A5};
float dec [6];

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

void loop()
{
  for(int i = 0; i<6 ; i++)
  {
    dec[i] = analogRead(ana[i]);
    Serial.println(dec[i]);
    delay(1000);
  }
}

How is this even possible?

this is the output result


texts: How can I configure the RFM95 LoRa module to emit packets at only 'one' particular frequency?

texts: I have created a LoRa gateway using a Pi3; I have used a RFM95 module for it. So, it is a single channel gateway, and I'm operating it at 868.1Mhz. But my LoRa node(also a RFM95, on an Arduino Uno), whenever transmits data, does so on various frequencies at random, and there seems to be no pattern to it. Hence a lot of data gets lost. How can i transmit data on a particular frequency only?


texts:
Items:

Arduino Uno
Laptop
7.4V 2s LiPo Battery
Neewer 30A ESC

Scenario:

The LiPo powers the ESC while the Laptop USB powers the Arduino. If I unplug the USB from Arduino is loses power (obviously) and when I plug in the ESC to the arduino I get power again to the Arduino. I need the USB plugged in to receive Serial information from the laptop and I need pow+gnd plugged into the Arduino or else I get a lot of PWM noise rendering my ESC useless.

ESC is 5V
USB is 5V

Question:

This is my due diligence to not blowing anything up. What is the safest way to plug in power from both USB and the ESC? Same voltage, difference sources. Or can I just connect the grounds and call it good?


texts: What GUI software/platform can I use to control my Arduino MP3 player over the serial port?

texts:
How would I make a GUI program on a different platform to control my Arduino MP3 player using the Arduino's serial port.

I would like the GUI program to show images like this for 'start':

...and this for 'next':

And when I click the images I want this GUI program to write strings to the Arduino's serial port. I want to do this because I have create an Arduino music player where a song can be selected by typing 'next', 'prev' and 'start' into the serial monitor.

Instead of using the serial monitor, I want to make a GUI program that has buttons that will send 'next' when I click the next button and 'start' when I click the start button.


texts: Latest news about alternative Arduino IDEs

texts:
I simply hate the default Arduino "IDE".
On Windows I use Visual Studio Code with the related plugin.

Now I have a Ubuntu machine and I'm looking for the definitive IDE.
Questions:

I'm not sure whether to use VSC I need to install the default IDE as well
is there something better?

By the way, I also have QtCreator, PHPStorm, MPLAB X, STM32Cube (Eclipse based).


texts: What is the relationship between the gain on the receiver and the delay time

texts:
I was conducting some research on wireless communication between a simple transmitter and receiver module using an Arduino. Now, I tested the channel accuracy and i received 14% error for a delay of one micro second. For a delay of 2 microseconds, my error was 0%, and for three microseconds, my error rate was 30%. I am not quite sure why the data would result in this. I think it possibly has something to do with the gain on the receiver and the delay time. Some sweet spot perhaps? Can anyone offer me some ideas/explanations? Also, sorry for any confusion in this question. I am happy to clarify.

Part 2:

Hey Everyone,

I also had a question regarding what purpose each of the following delay serves in wireless communication.

// Write each of the 8 bits
for (uint8_t i = 8; i > 0; --i)
{
  if (b & 1) // choose bit
    *reg |= reg_mask; // send 1
  else
    *reg &= inv_mask; // send 0

  tunedDelay(delay);// line in question ---------------------
  b >>= 1;
}

and the delay used in the regular blink program.

The regular delay used in the blink programs was what set the 2 microsecond delays.

Lastly, I am looking at the read and recv methods in the software serial library and i don't see any checks for start bits, so what's the point of writing one in the write method?


texts: Using rotary encoders with pin change interrupts

texts:
I'm using an Arduino Uno and two (3-pin) rotary encoders for a project. Since the loop takes a bit long and accuracy is important, I'd like to use interrupts to read the values from the rotary encoders. Also, pins 2 and 3 are occupied so I can't use hardware interrupts.

I'm using the Rotary library (github link) for the rotary encoders and the EnableInterrupt library (github link) for external interrupts. The Rotary library includes an interrupt example, but I couldn't manage to modify it to work with pin change interrupts. This is my current state (test code):

#include <EnableInterrupt.h>
#include <Rotary.h>

Rotary r = Rotary(2, 3);

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

  /* Original interrupt setup:
  PCICR |= (1 << PCIE2);
  PCMSK2 |= (1 << PCINT18) | (1 << PCINT19);
  sei();
  */

  enableInterrupt(2, interruptFunction, CHANGE);
  enableInterrupt(3, interruptFunction, CHANGE);
}

void loop() {

}

void interruptFunction() {

  Serial.println("Int. called");

  unsigned char result = r.process();
  if (result == DIR_NONE) {
    // do nothing
  }
  else if (result == DIR_CW) {
    Serial.println("ClockWise");
  }
  else if (result == DIR_CCW) {
    Serial.println("CounterClockWise");
  }
}

Everytime I turn the encoder for one step, the interruptFunction gets called a bunch of times (about 2~4) but the r.process() call never returns a value.

My current guess is that this has something to do with the rotary encoder outputting gray code, but I'm not quite sure how my approach differs from the Rotary interrupt example using hardware interrupts.

Hope you can help!


texts: How to turn a LED if ultranonic HC-SR04 reading is on defined range for some interval

texts:
My objective is if ultrasonic readings ranging between 1 to 10 cm and no distance change for 10 seconds or more, a LED will turn on. Here is my current code.

#define trigPin 7
#define echoPin 8
#define led 13
#define led2 12

long duration, distance, interval = 4000;
int detection = 0;

void setup() {
   Serial.begin (9600);
   pinMode(trigPin, OUTPUT);
   pinMode(echoPin, INPUT);
   pinMode(led, OUTPUT);
   pinMode(led2, OUTPUT);
   detection = millis();
}

void loop() {

   ultraSonic();

   if (distance > 0 && distance < 10 && (millis() - detection >= interval)) {
   digitalWrite(led, HIGH);
   digitalWrite(led2, LOW);
   } else {
   digitalWrite(led, LOW);
   digitalWrite(led2, HIGH);
   }

   Serial.print(millis());
   Serial.print(" - ");
   Serial.println(distance);

   delay(250);
}

void ultraSonic() {
   digitalWrite(trigPin, LOW);
   delayMicroseconds(60);
   digitalWrite(trigPin, HIGH);
   delayMicroseconds(60);
   digitalWrite(trigPin, LOW);
   duration = pulseIn(echoPin, HIGH);
   distance = (duration / 2) / 29.1;
}

Sorry for my bad english.
Cheers.


texts: using multiple hc-05 with one arduino mega

texts: please anyone help me build my project, i want to connect multiple smart phones to arduino mega using blutooth module hc-05 , I am working on real life home automation project and i don't have idea that can i use 4 Bluetooth modules with arduino mega . Requirement is max 4 smart phone connect to system , please anyone knowing about arduino please help ,i will be grateful . if u have any other suggestions tell me .


texts: 7-Segment Display with WS2312B and FastLED

texts:
I thought of the idea of using the WS2312B LED strip to drive a custom 7-Segment display. The project will require a large number of these displays, and driving them with a single Arduino (I'm thinking of an Arduino MEGA). For driving the LEDs I am using the FastLED library.

I wrote some code that drives a single display, It works, but I think It's possible to make it simpler, the code I wrote stores the digits in arrays, and uses these arrays in functions customized to each digit. here is an example:

//Digit Arrays:
byte digit0[]     = {0,1,2,3,4,5};
byte digit1[]     = {1,2};
byte digit2[]     = {0,1,3,4,6};
byte digit3[]     = {0,1,2,3,6};
byte digit4[]     = {1,2,5,6};
byte digit5[]     = {0,2,3,5,6};
byte digit6[]     = {0,2,3,4,5,6};
byte digit7[]     = {0,1,2};
byte digit8[]     = {0,1,2,3,4,5,6};
byte digit9[]     = {0,1,2,3,5,6};

The functions are something like this:

void AllOff(){
//Switch off All the LEDs in the segment. Should be off for 1 second
  for(int i=0; i<7; i++){
    leds[i] = CRGB::Black;
    FastLED.show();
  }
  //delay(1000);
}
void AllOn(CRGB myColor){
  //Switch on All the LEDs in the segment (should display 8)
  //The color of choice is #1E78A0
  for(int i=0; i<7; i++){
    leds[i] = CRGB (30,120,160);
    FastLED.show();
  }
  delay(1000);
}
void Print0(CRGB myColor){
  //Prints the digit 0:
  AllOff();
  ArraySize = sizeof(digit0);     //get the size of the array
  for(int i=0; i<ArraySize; i++){
    LED_Number  = digit0[i];      //get the LED number from the array
    leds[LED_Number]    = CRGB (myColor);  //Switch the LED on
    FastLED.show();
  }
}

When I call it in the code, I simply do something like this:

Print0(CRGB::Purple);
delay(500);

I have tried for the best part of the past two days to find a better way to go about this, but I couldn't. What I'm thinking is perhaps to create a function that would store all the digits instead of storing every one as an array, and then call it maybe within a for loop? something like

for(int i=0; i<10; i++){
    displaydigit[i];
    FastLED.show();
  }

Do you know of any library that has something similar, or perhaps any idea on how to achieve this?

Your assistance, as always, is greatly appreciated.

Thank You.


texts: Voice recognition without module, is it possible?

texts:
I'm trying to figure out how to process a voice signal for simple purposes. Wherever I look people using or suggesting recognition modules for Arduino.

What I'm wondering: is this possible to make a simple command recognition with Arduino, without modules?

I just simply want to attach a microphone to my Arduino and after I convert it I want to handle signal and program it in MATLAB or in an Arduino itself. How can I achieve that?

As you can see I'm newbie in this. Any help is appreciated. Thanks!


texts: Bootloader only works once with usb to serial module

texts:
When programming the Pro Mini using this USB-to-serial adapter the boot loader only works once. After the first programming the programmer is out of sync or not responding.

To be able to program the Pro Mini again I have to burn the bootloader using my Uno as an ISP.

Programming the Pro Mini through an Uno does not present the same problem.

Are the lock bits not being set properly or somehow overridden?


texts: can arduino on output mode sink current?

texts:
I have a arduino set below:

pinMode(1,OUTPUT);
digitalWrite(1,LOW);

Now, I am expecting 1.2mA current flow through the pin that is set as output. Is that accepted? If so, what it the max current a pin can sink?

The current comes from a pul up resistor on the line

note: I can't protect it with a diode.


texts:
I am trying to set up the low power module for an instance case,
I have installed the low power library but when I am using the
line

LowPower.powerDown (SlEEP_5S, ADC_OFF, BOD_OFF) ;

It is throwing an error stating that the 'SLEEP' was not declared in the scope.
Any suggestion for that ? Do I have to include a library for sleep too ?

#include "LowPower.h"
  /// DON' t worry about the setup and loop, i have defined all those.

This set of code is in

  void Loop()
    ...
    else
    {
       LowPower.powerDown (SLEEP_10S, ADC_OFF, BOD_OFF) ;


texts: ATtiny85. How do I burn a bootloader? What is the process?

texts:
I want to use all six I/O pins of an ATtiny85, that means also using the reset pin as an I/O pin, however, I found out that if I disable the RESET pin, I can no longer program the ATtiny using an ISP programmer.

However, I found out that there are bootloaders for ATtiny which, as far as I understand, allow me to program the ATtiny through USB, without the need of the RESET pin.

My question is: How do I burn such a bootloader (such as micronucleus for example) to the ATtiny85? And how do I need to connect the ATtiny to USB after that (like this?)? How do I program it after that? Keep in mind that in terms of burning bootloaders and modifying fuses, I am a complete newbie.

Also, I'm using the ArduinoISP sketch as my ISP programmer since I don't have a real ISP programmer, but as far as I read, that won't be a problem.

EDIT: I do have this thing I bought for a couple dollars on eBay, which I don't know how and if I need to to use:


texts: Multi tasking alternative on NodeMCU ESP8266

texts:
I'm trying to make an RGB LED strip controlled via Wi-Fi and IR. Until now, I just have made the Wi-Fi server, and It worked just fine. But I wanted to be able to turn the LED strip on and off via IR, the only problem is that I can't read IR data because of the web server, the only way to make that work would be using multitasking, which I think is impossible to make on NodeMCU ESP8266. Any other ideas on how to make it work?

I tried that way, it works sometimes, but the Wi-Fi function takes about 3 seconds to run, so I can't read IR data while this function is used, so it's pretty ineffective.
void loop() {

for (int i = 0; i <= 100; i++) {

   // READ THE VALUES

    delay(20);
}
wifiServer();
}

#include <ESP8266WiFi.h>

const char* ssid = ""; // SSID
const char* password = ""; // PASSWORD
String header;
bool onOffFactor;
int redVal, greenVal, blueVal;

#define green 16
#define blue 5
#define red 4
#define IR 2

WiFiServer server(80);

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

  onOffFactor = false;
  pinMode(red, OUTPUT);
  pinMode(green, OUTPUT);
  pinMode(blue, OUTPUT);
  pinMode(IR, INPUT);

  delay(10);
  Serial.print("Connecting to: ");
  Serial.print(ssid);
  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }

  Serial.println(ssid);
  server.begin();
  Serial.print("IP: ");
  Serial.print("http://");
  Serial.println(WiFi.localIP());

}
void loop() {

  for (int i = 0; i <= 100; i++) {

    if (digitalRead(2) == LOW) {
      if (onOffFactor == false) {
        analogWrite(red, 0);
        analogWrite(green, 0);
        analogWrite(blue, 0);

        onOffFactor = true;
      } else {
        analogWrite(red, redVal);
        analogWrite(green, greenVal);
        analogWrite(blue, blueVal);

        onOffFactor = false;
      }
    }
    delay(20);
  }

  wifiServer();
}

void wifiServer() {

  WiFiClient client = server.available();
  String request = client.readStringUntil('\r');
  client.flush();

  if (request.startsWith("GET /?")) {

    int startS = request.indexOf("?");
    int endS = request.indexOf("&");
    String reqStr = request.substring((startS + 1), endS);

    ///// STRING PROCESSING

    int rS = reqStr.indexOf("r");
    int gS = reqStr.indexOf("g");
    int bS = reqStr.indexOf("b");

    redVal = (reqStr.substring((rS + 1), gS)).toInt();
    greenVal = (reqStr.substring((gS + 1), bS)).toInt();
    blueVal = (reqStr.substring((bS + 1))).toInt();

    analogWrite(red, redVal);
    analogWrite(green, greenVal);
    analogWrite(blue, blueVal);

  }

      // SIMPLE HTML CODE
  client.println("<input type=\"text\" id=\"red\" name=\"RED\">-> RED

<input type=\"text\" id=\"green\" name=\"GREEN\">-> GREEN

<input type=\"text\" id=\"blue\" name=\"BLUE\">-> BLUE

send");
  client.println();
}


texts:
I want my arduino to give the output at a specified delay .The delay is calculated from a polynomial equation.

unsigned long t=40*Vin*Vin-760*Vin+4320;
delay(t);
digitalWrite(ledPin,HIGH);

but while doing this i was unable to get the delay accurately while observing it through oscilloscope??


texts: MAX232 chip fails to initialize properly with arduino

texts:
I have connected a MAX232 chip for RS232 communication with my Arduino.
The chip input is connected to Arduino Tx and it is getting power from external 3.3 volt dc power source.

My Arduino is also getting power from 12 volt DC external power source.

While I connect and start the device, the PC is not getting any data until I reboot the MAX232.

How do I make a robust setup so that after I turn the powers on, it starts transmitting. Even if connection to my PC has been lost.


texts: Does anybodyknow how to program Muscle Sensors v3?

texts:
#include <Servo.h>

const int x =  200

//Naming the servosServo
Servo servo1;
Servo servo2;
Servo servo3;
Servo servo4;
Servo servo5;
Servo servo6;

void setup()
{
  Serial.begin(9600);
  servo2.attach(10);
  servo3.attach(11);
  servo4.attach(3);
  servo5.attach(6);
  servo6.attach(5);
}

void loop()
{
  //Printing the EMG data
  Serial.println(analogRead(0));

  if (analogRead(5) > 200)
  {
    servo2.write(180);
    servo3.write(148);
    servo4.write(89);
    servo5.write(180);
    servo6.write(180);
  } else if (analogRead(0) < 200)
  {
    servo2.write(38);
    servo3.write(10);
    servo4.write(0);
    servo5.write(16);
    servo6.write(16);
  }

  delay(100);
}

I don't know if the problem is in the code or in the circuit.


texts: Arduino, Receiving Instant Time When Event Occurs

texts:
i am trying to figure out situation that i have mentioned about in the topic.

I am trying to get an event's time when it occurs. For example, i am trying to receive Diagnostic Port's data by Arduino CanBus shield and i want to print instant time on screen. For example whenever i receive RPM value from car at a time(time in terms of milisecond) i want to display that time on serial monitor. May be i will run the code for 2 hours. I know that i can use RTC for some time process, but i want to solve this situation without RTC.

Here is my code,

//Canbus.ecu_req(state[check % 3].pid, state[check % 3].buffer);
strcpy(state[check % 3].buffer, "HELLO !");
state[check % 3].time = millis();
state[check % 3].f1 = SD.open(state[check % 3].sdName, FILE_WRITE);     //  Open vehicles' variables sd file
state[check % 3].f2 = SD.open(state[check % 3].sdTimeName, FILE_WRITE);     // Open vehicles' variables time file
if (state[check % 3].f1 && state[check % 3].f2) {
    state[check % 3].f1.println(state[check % 3].buffer);   // Write pid values
    state[check % 3].f2.println(state[check % 3].time);     // Write time values
    Serial.println(state[check % 3].buffer);
}

As you can easily see from my code, i assigned millis() to value of my variable's time when it receives OBD value from car.


texts: How can I make an H-bridge using NPN transistor?

texts: I am new to arduino and I wanted to make an h-bridge because it is not easily available in india. I want to control the h-bridge using arduino uno r3 board and 2n2222A transistors and 1n4001 Diodes if necessary. I want this h-bridge to control two motors in a single direction. If possible pls include the friting diagram. I had created the circuit using NPN transistor and flyback diode and a resistor for both motors individually, I am posting the diagram , This is the link to the tutorialtutorial link


texts: the code and the actual output didn't match

texts:
i want to make the stuff, which the output is written from the analogread, but when the A3 == HIGH, the output pin 9 is used, but when the A3 == LOW, the output pin 10 is used, and when i simulate it on proteus, it seems not the same as i mean, what's wrong with the code, please need your help.

  int hasil
  int reado;
  int z;
  int baca;
  bool en = false;
  void setup() {
  // put your setup code here, to run once:

  TCCR1A = 0b00100010;
  TCCR1B = 0b00011001;
  TCCR0A = 0; TCCR0B = 0;
  ICR1 = 100000;//disable millis, delay and mciroseconds function
  //disable millis, delay and mciroseconds function

   // put your setup code here, to run once:
  Serial.begin(115200);
  pinMode(A2, INPUT); pinMode(A3, INPUT);
  pinMode(9,OUTPUT); pinMode(10,OUTPUT);
  }

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

 hasil = analogRead(A2);
 baca = digitalRead(A3);
 for (z=0; z<=hasil; z++)
 reado = map (hasil, 0, 255, 0, ICR1);
 if (hasil > 30 && baca == HIGH)
 {analogWrite(9,hasil); analogWrite(10,0);}
 else if (hasil >30 && baca == LOW)
 {analogWrite(9,0); analogWrite(10,hasil);}
 else if (hasil<30)
 {analogWrite(9, 0);
 analogWrite(10, 0);}}


texts: Arduino ethernet shield not getting correct IP

texts:
I have a very simple sketch which I'm using to (try to) prove out an ethernet shield. The complete sketch is below. When I upload the sketch, the IP address that the shield gets is 0.140.140.140, which is incorrect. I just received the shield today from SparkFun, it is this one. Am I doing something wrong, or is my shield  and/or Arduino broken? The Arduino is an Uno R3. The sketch works otherwise (the LED blinks as expected).

Sketch:

#include <SPI.h>
#include <Ethernet.h>

// Network information
byte mac[] = {0xDE, 0xAD, 0xBE, 0xCF, 0xFE, 0xEE };
byte ip[] = { 172, 31, 42, 201 };

void setup() {
  pinMode(4,OUTPUT);
  digitalWrite(4, HIGH);
  delay(1);

  // initialize serial:
  Serial.begin(9600);
  Serial.println("Starting sketch...");
  Ethernet.begin(mac,ip);
  delay(1000);
  Serial.println(Ethernet.localIP());
  Serial.println("Setup done.");
  pinMode(13, OUTPUT);
}

void loop() {
  digitalWrite(13,HIGH);
  delay(1000);
  digitalWrite(13,LOW);
  delay(1000);
  Serial.println(Ethernet.localIP());
}


texts: How do I add additional compiler switches in Visual Studio

texts:
Using Visual Studio to program my Arduino. I want to add additional compiler switches and include paths.

How can this be done?


texts: Is it possible to make a touchpad for PC using arduino and a touchscreen display?

texts:
What would be the difficulty for such project?
What components would be best fit for communicating gestures to windows (thought about arduino uno r3 and LCD TFT 3.5” UNO)


texts:
I bought a 9 DOF IMU from AliExpress (pictures below), asking because this seems to be somewhat of a common issue (and I'm a bleeding noob). I tried setting up this board using example codes from Adafruit - presuming this would work and it's a compatible board (and it just looked exactly the same). However, surprise - several errors.

Using this guide I attempted to run the pitchrollheading example - it reports LSM303 not found. The wiring is according to this guide, A4 (SDA) and A5 (SCL) are connected, 5V in, Ground of IMU to Ground of Arduino (Arduino uno, like in the guide)

Next I debugged the lines on the board using the multimeter: 5V on line in vs ground, 5V on the SDA/SDC lines (seemed fine)

Then I debugged using the i2cdetect library, however it reported empty.
 0  1  2  3  4  5  6  7  8  9  a  b  c  d  e  f
 00:          -- -- -- -- -- -- -- -- -- -- -- -- --
 10: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
 20: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
 30: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
 40: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
 50: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
 60: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
 70: -- -- -- -- -- -- -- --

Using analog read I can get values that seem to change with board movement, that would confirm that - in theory - the board works.

Questions

Making sense from debugging: What could be somre reasons the board not listed using the i2cdetect library (also tried a script)?
Is there an easy way (or would you recommend spending time to investigate) to use the rawdata from the arduino's analog in lines to compute pitch,roll and heading?
Would a project like this be typically orders of magnitude easier to set up with a raspberry pi (I have one setup and ready)? (more libraries?)
Are IMU's usually easy to setup, and is it likely this would be easier with a more expensive IMU (e.g. MPU9250/6500)?

Thank you in advance, and please remember: I'm a noob, I ask for your patience and advice.


texts:
I build .hex files for Arduino. How can I do this in Linux? I use the Linux distro  Mint 17.2.

I need a program to make [.hex files] (in Linux).

Can anyone help me?


texts: Can I use an ATmega328 alone without anything and what is the max voltage I can power the atmega328 with

texts:
Okay 2 questions. If I am to replace the Arduino with an ATmega328 programmed with a standard blink on pin 13, is this configuration correct, do I still need oscillators and whatnot?

Second question is, what is the max voltage I can power the ATmega328 with without frying it? I have seen conflicting answers of this on the net. Some have said 5V while some say 6V can someone clarify?


texts:
I have um esp 01 on port 2 and 3 from my Arduino, I can send several characters, but I cannot to receive many characters, my code is this:

#include <SoftwareSerial.h>

//TX RX
SoftwareSerial esp8266(2, 3);

void setup() {
    Serial.begin(9600);
    esp8266.begin(19200);
    ...
}

...

void loop() {

...

    if (esp8266.available() > 0) {

        String string = "";

        if (esp8266.find("[msg]:")) {
            string = esp8266.readStringUntil('\r');
        }

        /* I tried this too, but don't worked
        while (esp8266.available()) {
            string += (char) esp8266.read();
        }
        */

        Serial.print("\r\n" + string);
    }

...

I can receive only 32 caracteres, I don't why.

I have this code python to send the informations:

import socket

class socketClient(object):
    socket = None

    def __init__(self, ip, port):
        self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.socket.connect(((ip, port)))

    def send(self, msg):
        self.socket.send(msg)

    def close(self):
        self.socket.close()

    def receive(self):
        return self.socket.recv(10240)

status = raw_input('Entre com o estado: ')
json = '[msg]:' + status + '\r\n';
print json

#This part was to test with a local server python
#socket = socketClient('127.0.0.1', 7000)

socketClient('192.168.0.43', 80)
socket.send(json)
msg = socket.receive()
print(msg.decode('utf-8'))
socket.close()

UPDATE

  I made some tests using the native RX TX ports, I sent command
  manually and connected to the network, and the String was complete,
  then the real problem is on code, but how to I will take this string?

UPDATE

If I do this, its works, but I need get this information and put in a String.

while (esp8266.available() > 0) {
    Serial.write(esp8266.read());
}

It is showing all information on serial monitor.


texts:
I'm working on this project where I have interfaced a LED strip (a two wire LED strip) with this Arduino (its not an Uno). I have setup every thing correctly according to this instructable. I'm able to make a simple blinky pattern and I turn it on/off with an Android app I made to communicate with the Arduino using Bluetooth on my phone. Cool.

What I cannot understand is, since the strip is two wired, how should I address individual LEDs on the strip to make more complex patterns? Can I use bit shifts? Reading an article from Makezine (insufficient reps to post more than 2 links), it says that I should connect the strup directly to the output pin. IMO, this will fry the Arduino or in a less virulent sway, not light up the strip in any way.


texts: Im using the arduino Micro pro to read the data out of a temperature sensor (lm35). The program is compiling and NOT uploading, but when I try and open the serial monitor is says: Error opening serial port 'COM1'. (Port busy)


texts: I have the code printing the data I need but don't know how to connect the data on ESP8266 IP web server

texts:
#include "DHT.h"
   #include "NewPing.h"
   #include <SoftwareSerial.h>

   #define DEBUG true
   SoftwareSerial esp8266(11,10);
   #define DHTPIN 2        // DHT-11 Output Pin connection
   #define DHTTYPE DHT11   // DHT Type is DHT 11 (AM2302)
   #define TRIGGER_PIN 4
   #define ECHO_PIN 3
   #define MAX_DISTANCE 400

    NewPing sonar(TRIGGER_PIN,ECHO_PIN,MAX_DISTANCE);
float hum;
float temp;
    DHT dht(DHTPIN, DHTTYPE);

void setup() {

   Serial.begin (9600);
   dht.begin();

   pinMode(TRIGGER_PIN, OUTPUT);
   pinMode(ECHO_PIN, INPUT);

   sendData("AT+RST\r\n",2000,DEBUG);
   sendData("AT+CWMODE=2\r\n",1000,DEBUG);
   sendData("AT+CIFSR\r\n",1000,DEBUG);
   sendData("AT+CIPMUX=1\r\n",1000,DEBUG);
   sendData("AT+CIPSERVER=1,80\r\n",1000,DEBUG);

 }

 void loop()

 {

 delay(2000);  // Delay so DHT-11 sensor can stabalize

   hum = dht.readHumidity();  // Get Humidity value
   temp= dht.readTemperature();  // Get Temperature value

 digitalWrite(TRIGGER_PIN, LOW);
 delayMicroseconds(2);
 digitalWrite(TRIGGER_PIN, HIGH);
 delayMicroseconds(10);
 digitalWrite(TRIGGER_PIN, LOW);

   long duration,distance;
   duration= pulseIn(ECHO_PIN,HIGH);
   distance = duration/58.2;

   Serial.print("Humid: ");
   Serial.print(hum);
   Serial.print(" %, Temp: ");
   Serial.print(temp);
   Serial.print(" C, ");
   Serial.print("Distance: ");
   Serial.print(distance);
   Serial.println(" cm");

   delay(50);

  if(esp8266.available())

   is sending a message
 {
   if(esp8266.find("+IPD,"))
 {
 delay(1000);

 int connectionId = esp8266.read()-48;

  /* We are subtracting 48 from the
  output because the read() function returns
  the ASCII decimal value and the
  first decimal number which is 0 starts at 48*/

  String webpage = "
IOT Garbage Monitoring System
";
  webpage += "

";

  if (distance<5)
 {
  webpage+= " Trash can is Full";
 }
   else{
   webpage+= " Trash can is Empty";
    }
   webpage += "

";
   String cipSend = "AT+CIPSEND=";
   cipSend += connectionId;
   cipSend += ",";
   cipSend +=webpage.length();
   cipSend +="\r\n";

   sendData(cipSend,1000,DEBUG);
   sendData(webpage,1000,DEBUG);

   String closeCommand = "AT+CIPCLOSE=";
   closeCommand+=connectionId;
   closeCommand+="\r\n";
   sendData(closeCommand,3000,DEBUG);

   }
   }
   }

   String sendData(String command, const int timeout, boolean debug)

   {

   String response = "";
   esp8266.print(command);
   long int time = millis();

   while( (time+timeout) > millis())
   {
   while(esp8266.available())
   {
   char c = esp8266.read();
   response+=c;
   }
   }
   if(debug)
      {
     Serial.print(response);
      }
     return response;
      }