texts: Problem using an array inside a switch statement

texts:
I am having a problem when using a switch statement to check for something inside an array. I am using an int as my switch, then I compare the character arrays using strstr. So it reads like this:

void function(char *buffer, uint32_t size){
  char *p=(char*)malloc(compareSize); //compareSize is the size of the text to be compared
  #define TXTCOMPARE1 (char*)"Sample Text 1"
  #define TXTCOMPARE2 (char*)"Sample Text 2"
  #define TXTCOMPARE3 (char*)"Sample Text 3"
  switch(intCompare){
    case COMPARE1 :
      p = strstr(buffer,TXTCOMPARE1); break;
    case COMPARE2 :
      p = strstr(buffer,TXTCOMPARE2); break;
    case COMPARE3 :
      p = strstr(buffer,TXTCOMPARE3); break;
  }
  if(p!=NULL) { Serial.println("Success!"); }
  else { Serial.println("No match"); }
    memset(&p,0,sizeof(p);
}

This method does not work and p is always NULL. However, when I write it out without the switch() it compares just fine:

//using the same p declaration as above
p = strstr(buffer,TXTCOMPARE1);
if(p != NULL) { Serial.print("Success:"); }
else { Serial.print("No Match"); }

Why would the switch statement give me different results for what is basically the same function call?

Edit: Actually it seems to break everywhere when I set more than one call to p = strstr(...). When there is only one strstr it works, when two or more are used, it does not...


texts: How does an LED in an LED-strip like WS2811 know when it should be on or off

texts:
I was experimenting with an Arduino board and an LEDstrip WS2811
it works all perfect, but I do not understand how a particular led knows when it is called or adressed. Does every led have a unique address?


texts: LED doesn't turn on as specified on code State Machine

texts:
This is the question from the homework I'm doing "Design and implement a state machine with a single button to turn on and off two LEDs The first LED should be turned on and off with a quick press of the button, the second LED should turn on and off with a long press (1 second)."

I have this code

int state_s1 = 0;
int state_s2 = 0;
int state_s3 = 0;
int state_s4 = 0;
int state_prev_s1 =0;
int ledPin2 = 8;
int ledPin = 9;
int boton = 10;
int boton2 = 11;
int val_s1 = 0;
unsigned long t_0_s1 = 0;
unsigned long t_s1 = 0;
unsigned long t_s2 = 0;
unsigned long tiempo = 50;
unsigned long bounce_delay_s1 = 5;
unsigned long bounce_delay_s2 = 1000;
boolean prendido = false;
boolean prendidoP = false;

void setup()
{
  pinMode(boton, INPUT_PULLUP);
  pinMode(boton2, INPUT_PULLUP);
  pinMode(ledPin, OUTPUT);
  pinMode(ledPin2, OUTPUT);
  Serial.begin(9600);

}

void loop()
{

  SM_s1();

  if(prendido == true)
  {
    led();
  }

  if(prendidoP == true)
  {
    led2();
  }

   Serial.print("state 1 =");
   Serial.println(state_s1);

   Serial.println("************");

}

void led()
{

  switch(state_s1)
  {
    case 0:         //OFF
    digitalWrite(ledPin, LOW);
    t_0_s1 = millis();
    state_s1 = 1;
    break;

    case 1:         //WAIT
    t_s1 = millis();
    if(t_s1 - t_0_s1 >= tiempo)
    {
      state_s1 = 2;
    }
    break;

    case 2:         // ON
    digitalWrite(ledPin, HIGH);
    t_0_s1 = millis();
    state_s1 = 3;
    break;

    case 3:         //WAIT
    t_s1 = millis();
    if(t_s1 - t_0_s1 >= tiempo)
    {
     state_s1 = 0;
    }
    break;

  }
}

void led2()
{

  switch(state_s4)
  {
    case 0:         //OFF
    digitalWrite(ledPin2, LOW);
    t_0_s1 = millis();
    state_s4 = 1;
    break;

    case 1:         //WAIT
    t_s1 = millis();
    if(t_s1 - t_0_s1 >= tiempo)
    {
      state_s4 = 2;
    }
    break;

    case 2:         // ON
    digitalWrite(ledPin2, HIGH);
    t_0_s1 = millis();
    state_s4 = 3;
    break;

    case 3:         //WAIT
    t_s1 = millis();
    if(t_s1 - t_0_s1 >= tiempo)
    {
     state_s4 = 0;
    }
    break;

  }
}

 void SM_s1()
 {
  switch(state_s2)
  {
    case 0:         //RESET
    state_s2 = 1;
    break;

    case 1:        //START
    val_s1 = digitalRead(boton);
    if(val_s1 == LOW)
     {
      state_s2 = 2;
     }
    break;

    case 2:         // GO!
    t_0_s1 = millis();
    state_s2 = 3;
    break;

    case 3:         //WAIT
   if(val_s1 == HIGH)
     {
      state_s2 = 0;
     }

    t_s1 = millis();

    if(t_s1 - t_0_s1 >= bounce_delay_s1)
    {
      state_s2 = 5;
    }
    break;

    case 5:         //ARMED & WAIT
    t_s2 = millis();
    val_s1 = digitalRead(boton);
    if(val_s1 == HIGH && t_s2-t_s1 < bounce_delay_s2)
     {
      state_s2 = 4;
     }

     if(t_s2-t_s1 >= bounce_delay_s2)
     {
      state_s2= 6;
     }

    break;

    case 4:       //TRIGGERED
    state_s2 = 0;
    prendido = not prendido;
    break;

    case 6:     // ARMED 2
    state_s2 = 0;
    prendidoP = not prendidoP;
    break;

}
}

It will work the first time but then the LEDs won't turn off and sometimes when the button is pressed hard, it will turn both LEDs on, please help me.


texts:
I am trying to connect my A7 to my Arduino Uno but I can't find a way to communicate with it. I searched a lot on the internet to find some schemes but not one of them worked. Here is my actual setup:

ARDUINO              A7

PIN 6      <=>       URXD
PIN 7      <=>       UTXD
GND        <=>       GND
5V         <=>       5V

Here is my code:

#include<SoftwareSerial.h>
SoftwareSerial myserial(6,7);//RX,TX

void setup() {
  Serial.begin(9600);
  myserial.begin(115200);
  Serial.println("Starting...");
}

void loop() {
   delay(1000);
   myserial.println("AT");
   Serial.println(myserial.read());
}

I tried by connecting USB instead of 5V, both of them, connecting the POWER pin, or interchange 6 and 7, pressing the power button, with different delays, different baud rates, but I always get the same output on my computer:

Starting...
-1
-1
-1
-1
...

Sometimes it goes 0 when I plug the USB and press the power button. The LED on the A7 is responding when I press the button and sometimes it powers up the circuit.

I also tried this solution with really simple code:

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

void loop() {
}

Again with different bauds rates but the compiler outputs an error:

avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 2 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding
...

So I don't know what is wrong. Maybe the board is not working but it's most certainly my mistake, so I am asking for your help to solve this puzzle.

Thank you!


texts: Script on pc only gets 640 characters via serial

texts:
I experience that if the Arduino (Teensy 3.2) writes a rather long stream of characters to serial, the python script on the other end only receives the first 640 characters. I have found this result both by printing chars, printing lines and by using ArduinoJson's prettyPrintTo(Serial).

Note, that it does not matter what chunks of characters I read in the Python scripts, whether it is read(5) or read(1000).

With the Arduino Serial Monitor, I get all the data, ie more than the 640 characters.

From what I can understand, it is not possible for a sketch to write "too fast" or "too much" to the serial, so there must be something on the pc side receiving the data. However, the Python script for some reason does not get all the data.

What is the problem here? Where should I look for the problem/solution? Perhaps this is more a Linux or Python question, but I will try here.

Sketch - printLines()

void printLines() {
  for (int i=0; i<100; i++) {
    // length below is 40 incl end of line character
    Serial.printf("abcdefthijklmnopqrstuvxyz123456789--%03d\n", i);
  }
}

void setup() {
  Serial.begin(9600);
  delay(500);
  printLines();
  //printChars();
  //printJson();
}

void loop() {}

Sketch - printChars()

void printLines() {
  for (int i=0; i<1000; i++) {
    Serial.write('x');
  }
}

Sketch - printJson()

void printJson() {
  StaticJsonBuffer<10000> jsonBuffer;
  JsonArray &root = jsonBuffer.createArray();
  for (int i=0; i<700; i++) {
    root.add(i);
  }
  root.prettyPrintTo(Serial);
}

Python script

import serial

ser = serial.Serial('/dev/ttyACM0')
ser.timeout = 0.5

# PARAMETERS:
# (As long as num_iterations*num_chars >= 640, EXACTLY 640 characters are read)
num_chars = 100
num_iterations = 10

chars_read = 0
for i in range(num_iterations):
    s = ser.read(num_chars)
    chars_read += len(s)
    print("### i: %d, reading %d chars, char %d to %d, len(s): %d, total chars: %d"
        % (i,num_chars, i * num_chars, i * num_chars + num_chars -1, len(s), chars_read ))

Terminal output

jan@jan:~/Desktop/batlogger/localserver$ sudo python localserver.py
### i: 0, reading 100 chars, char 0 to 99, len(s): 100, total chars: 100
### i: 1, reading 100 chars, char 100 to 199, len(s): 100, total chars: 200
### i: 2, reading 100 chars, char 200 to 299, len(s): 100, total chars: 300
### i: 3, reading 100 chars, char 300 to 399, len(s): 100, total chars: 400
### i: 4, reading 100 chars, char 400 to 499, len(s): 100, total chars: 500
### i: 5, reading 100 chars, char 500 to 599, len(s): 100, total chars: 600
### i: 6, reading 100 chars, char 600 to 699, len(s): 40, total chars: 640
### i: 7, reading 100 chars, char 700 to 799, len(s): 0, total chars: 640
### i: 8, reading 100 chars, char 800 to 899, len(s): 0, total chars: 640
### i: 9, reading 100 chars, char 900 to 999, len(s): 0, total chars: 640


texts: Let's say we have two buttons - button 1 and button 2. What I need to do is to do something (like turn LED on) when button 1 is press, then button 2 is pressed. I can do it realy simple by just using two boolean variables, but how can we tell button 1 was the first pressed button?


texts:
I am just wondering if it is possible to check a string for specific characters.  For example if my string is String mystr = "test"; and I wanted to check for the letter t at the beginning and if it is NOT there do something how would I go about this?

I have read about string.startsWith(string2); however it returns true or false, I want to be able to do "XYZ" if "ABC" isn't satisfied, and it would seem that string.contains isn't a thing.

To paraphrase, I am trying to create an if statement that will evaluate if a string starts with a certain character(s) and will do something if this condition is NOT met.


texts:
I am trying to use an external ADC with my UNO for very precise measurement of my signal.
The ADC which I am using is ADS1115.

http://henrysbench.capnfatz.com/henrys-bench/arduino-voltage-measurements/arduino-ads1115-module-getting-started-tutorial/

This is the site which I am referring to.It says the default reference voltage of the PGA gives a resolution of 188microvolt per bit.It also indicates towards changing the reference voltage to 2.048, to still increase the resolution per bit.

Can you please guide me in how to achieve this 2.048V.

Update:
https://www.google.co.in/url?sa=t&rct=j&q=&esrc=s&source=web&cd=3&cad=rja&uact=8&ved=0ahUKEwiFpq3P89vNAhXJro8KHa6IC04QFggpMAI&url=https%3A%2F%2Fcdn-learn.adafruit.com%2Fdownloads%2Fpdf%2Fadafruit-4-channel-adc-breakouts.pdf&usg=AFQjCNGhdMw47MRlXolMiMoHdsTwKMwMow

It seems that by adjusting the gain (page number 16-17 of 18) we can achive it.

WHat I need to know now, is where should I put that piece of code

      ads1115.setgain(...)

in void loop() or in void setup()

Thanks

Anupam


texts: Is defining a function improves speed rather computing average for each analog input separately

texts:
My Arduino controller reads data coming from four different sensors. After the data is read, I individually compute four input average values. I understood that I am having the same lines of code repeated four times. Instead, I want to define a function with an analog pin as input and compute the average. My code is working fine. The question I have is, will this function improve the speed, reduce memory?
My code:
// Samples average
sample_cnt = 1000;

//// Input the pin number and compute average value
float Average_input_value(int analog_pin){
  float avg_val = 0;
  for(int i=0;i<sample_cnt;i++){
    avg_val += analogRead(analog_pin);
  }
  // Divide by Sample count to get the average value
  avg_val = avg_val/sample_cnt;
  return avg_val;
  }


texts: Can I use 1-byte datatypes to store digital input?

texts:
I am reading the docs on DigitalRead() and wondering why it stores seemingly boolean HIGH and LOW inputs in int data type variable.

I have two issues with that:

int is 2-byte, while bool and uint8_t are 1-byte so it seems like a waste of memory for no benefit whatsoever.
It gets me confused when reading the code about whether the input came from digital or analog since int can have a wide range.

Is there any particular reason for storing digital inputs as int?

EDIT: bool and uint8_t are out of the question as per the answer below. int8_t still looks suitable for the purpose though.


texts: Wifi REST API GET call - how to concatenate and pass URL parameters?

texts:
I'm not too familiar with the Arduino C++ language, but I would like to get this native code to work.

In curl this works:

  curl "http://access.alchemyapi.com/calls/text/TextGetTextSentiment?text=i+feel+great&outputMode=json&apikey=my-apikey"^C

So I am trying to use a WiFi client for the same request but it seems the passing and parsing of the URL parameters is causing a problem.

sprintf(request,"/calls/text/TextGetTextSentiment?apikey=%s&text=%s&outputMode=%s","31adba6dfc3a879b88762f50efc9f892bd573207", "i+feel+great", "json");
Serial.println(request);

When I print the request, everything after the & gets truncated.

  char serverName[] = "access.alchemyapi.com";
  if(client.connect(serverName,port) == 1)
  {
    sprintf(outBuf,"GET %s HTTP/1.1",page);
    client.println(outBuf);
    sprintf(outBuf,"Host: %s",serverName);
    client.println(outBuf);
    client.println(F("Connection: close\r\n"));
  }

This works (HTTP status 200, though with missing parameters error from the API service) if I only pass in 1 parameter.


texts: Arduino UNO SPI Serial Clock (Pin 13 SCK) gives no output, but Blink Example (Pin 13 LED) works

texts:
I was attempting to use an SPI library and DAC device (Library AD57X4) for the first time, when I realized that the Arduino UNO Pin 13 was not outputting a clock signal (something I expected it to do).

Using a serial analyzer I can sample at 16MHz, yet nothing comes out of UNO Pin 13 except maybe a very occasional noise blip.  After no luck with the AD57X4 library, I wrote this simple program to try to get SPI clock signal on UNO Pin 13.  Setting UNO Pin 13 to OUTPUT makes no difference.

#include <SPI.h>

void setup() {
  //pinMode(13, OUTPUT);
  SPI.begin();

}

void loop() {
  SPI.transfer(0x00);
}

I do get a signal on UNO Pin 11 (MOSI), frequency 381 kHz.  This signal is due to SPI.transfer(0x00); , as it disappears when the line is removed.  Although likely irrelevant to the question, I noticed some periodic 6us gaps every ~1ms on this UNO Pin 11 (MOSI) signal.

The Blink Example Works:

    // the setup function runs once when you press reset or power the board
void setup() {
  // initialize digital pin LED_BUILTIN as an output.
  pinMode(LED_BUILTIN, OUTPUT);
}

// the loop function runs over and over again forever
void loop() {
  digitalWrite(LED_BUILTIN, HIGH);   // turn the LED on (HIGH is the voltage level)
  delay(1000);                       // wait for a second
  digitalWrite(LED_BUILTIN, LOW);    // turn the LED off by making the voltage LOW
  delay(1000);                       // wait for a second
}

I tried monitoring UNO ICSP header pin 3 (SCK), however there is no signal for either the SPI or Blink programs.

UPDATE:
I switched over to an Arduino NANO that I had around and was able to get this output.  I expected the clock to be high frequency and continuous for SPI.  The MOSI output is the same 381 kHz that I observed earlier.

#include <SPI.h>

void setup() {
  pinMode(13, OUTPUT);
  SPI.begin();

}

void loop() {
  SPI.transfer(0x00);
}

EDIT:
Here is a schematic of my circuit.  I am using an EVAL-AD5754R Evaluation Board from Analog Devices.  Here is a link to the AD5754 chip data sheet.  I'm providing 5V power through the J7 terminal (via the UNO), and supplying the SPI connections through the J8 header. The EVAL-AD5754R board works perfectly via USB and their software, but now I am transitioning to controlling it through Arduino/SPI.  As you can see I'm temporarily using a 12V battery for the analog voltage supply - this is until I build a regulated circuit.  J8 DGND pins are shown unconnected on the schematic below, but I've tried connecting one of them to the UNO's GND to no effect.

This is the configuration of the linkers which act to configure the eval board:

This is an annotated table describing J8 header connections (UNO <-> EVAL-AD5754R):


texts:
I have two Arduino boards and I want to make them communicate via I2C. The first board (slave) should read a temperature value from a DS18B20 sensor (OneWire) and send it to the second board (master) via I2C.

So, I tried to merge some code from the standard examples (Wire/master_reader, Wire/slave_sender and dallas/simple).

When I use the two sketches bellow, the serial monitor of the master board is printing the "hello " message, but when I enable the request temperature lines (slave code)

sensors.requestTemperatures();
sensors.getTempCByIndex(0);

the serial monitor shows nothing.

I wander if there is a conflict between OneWire and I2C, or if I've made some serious mistakes in the code.

Any suggestions would be appreciated.

Master

#include <Wire.h>

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

void loop(){
    Wire.requestFrom(2, 6);
    while(Wire.available()){
        char c = Wire.read();
        Serial.print(c);
        }
    delay(500);
   }

Slave

#include <Wire.h>
#include <OneWire.h>
#include <DallasTemperature.h>
#define ONE_WIRE_BUS 2
OneWire oneWire(ONE_WIRE_BUS);
DallasTemperature sensors(&oneWire);

void setup(){
    sensors.begin();
    Wire.begin(2);
    Wire.onRequest(requestEvent);
 }

void loop(){
}

void requestEvent(){

    //sensors.requestTemperatures();
    //sensors.getTempCByIndex(0);

    Wire.write("hello "); // respond with message of 6 bytes
}


texts: Additional boards manager option is missing from Arduino IDE

texts: I am new to Arduino. For the project I am trying to do, I want to install the ESP8266 extension. But the additional boards manager URL option is missing from the Arduino IDE. What should I do to add the extension?


texts: Arduino PWM LED blinking on four pins, each pin's intensity and time period based on the previous pin

texts:
I am trying to make four LEDs glow using my Arduino, based on some relationship between them in terms of brightness and the time for which LEDs glow.

For example, the relationships are:

pin_3_value = 250  // LED 1 intensity
pin_5_value = 1.2 * pin_3_value // LED 2 intensity
pin_7_value = 1.1 * pin_5_value  // LED 3 intensity
pin_13_value = 0.59 * pin_7_value  // LED 4 intensity

time_till_led_1_on = 100
time_till_led_2_on = time_till_led_1_on * 1.2
time_till_led_3_on = time_till_led_2_on * 2.4
time_till_led_4_on = time_till_led_3_on * 1.2

I understand that only a fixed set of values are permitted as input to the analogWrite(). Is there some way to implement this relationship on the Arduino? I cannot use a digitalWrite(), as the output of PWM pins are used for something else; making the LED glow is just for testing purposes.

The code I have written so far:

// Brightness level for the four pins

int Brightness_1 = 255;
int Brightness_2 =  Brightness_1 * 2;
int Brightness_3 = Brightness_2 * 3;
int Brightness_4 = Brightness_3 * 4;

// Delay or time between  LED turn off and next LED turn ON

int Delay_1 = 500;
int Delay_2 =  Delay_1 * 1.1;
int Delay_3 = Delay_2 * 1.2;
int Delay_4 = Delay_3 * 1.3;

int pins[] = { 2, 4, 5, 7 }; // An array of pin numbers

void setup()
{
    int i;
    for (i = 0; i < 4; i++) // The array elements are numbered from 0  to num pins - 1
        pinMode(pins[i], OUTPUT); // Set each pin as an output
}

void loop()
{
    // Loop through each pin...
    analogWrite(pins[0], Brightness_1 ); // Turning it on,
    delay(Delay_1);                      // pausing,
    analogWrite(pins[0], 0);             // and turning it off.

    analogWrite(pins[1], Brightness_2); // Turning it on,
    delay(Delay_2);                     // pausing,
    analogWrite(pins[1], 0);            // and turning it off.

    analogWrite(pins[2], Brightness_3); // Turning it on,
    delay(Delay_3);                     // pausing,
    analogWrite(pins[2], 0);            // and turning it off.

    analogWrite(pins[3], Brightness_4); // Turning it on,
    delay(Delay_4);                     // pausing,
    analogWrite(pins[3], 0);            // and turning it off.
}

How can I make this work?


texts: Audio Signal to LED Lights Code Speed Improvement

texts:
I wrote this code that inputs audio from a jack (DC offset at 2.5V), performs the fft on a portion of the data, and then outputs a signal to an LED light strip dependent upon which frequency has the highest magnitude. It works but it would be nice if it was faster. Can anyone help out?

#include <arduinoFFT.h>
#include <FastLED.h>

arduinoFFT FFT = arduinoFFT();

const uint16_t samples = 128; //This value MUST ALWAYS be a power of 2
const double samplingFrequency = 16000;
double vReal[samples];
double vImag[samples];

int freqBounds[] = {0,300,500,800,2000,8000};

int colorValue = 0;
int sensorValue = 0;

#define SCL_INDEX 0x00
#define SCL_TIME 0x01
#define SCL_FREQUENCY 0x02
#define SCL_PLOT 0x03

#define LED_PIN   7
#define NUM_LEDS  5

CRGB leds[NUM_LEDS];

void setup()
{
  Serial.begin(115200);
  pinMode(A0, INPUT);
  FastLED.addLeds<WS2812, LED_PIN, GRB>(leds, NUM_LEDS);
  for(int i = 0; i < NUM_LEDS ; i++) {
      leds[i] = CRGB(0,0,0);
  }
  FastLED.show();
}

void loop()
{

  for (uint16_t i = 0; i<samples; i++){
    vReal[i] = int8_t(analogRead(A0));
    vImag[i] = 0.0;
    delay(1/samplingFrequency);
  }

  FFT.Windowing(vReal, samples, FFT_WIN_TYP_HAMMING, FFT_FORWARD);  /* Weigh data */
  FFT.Compute(vReal, vImag, samples, FFT_FORWARD); /* Compute FFT */
  FFT.ComplexToMagnitude(vReal, vImag, samples); /* Compute magnitudes */
  double x;
  double v;
  FFT.MajorPeak(vReal, samples, samplingFrequency, &x, &v);

  if (v>300){

    if (x>=freqBounds[0] && x<freqBounds[1]){
      Serial.print("BASE ");
      colorValue = (x - freqBounds[0]) * 255 / (freqBounds[1] - freqBounds[0]);
      leds[0] = CRGB(0,colorValue,255);
    }
    if (x>=freqBounds[1] && x<freqBounds[2]){
      Serial.print("TWO  ");
      colorValue = (x - freqBounds[1]) * 255 / (freqBounds[2] - freqBounds[1]);
      leds[0] = CRGB(0,255,255-colorValue);
    }
    if (x>=freqBounds[2] && x<freqBounds[3]){
      Serial.print("MID  ");
      colorValue = (x - freqBounds[2]) * 255 / (freqBounds[3] - freqBounds[2]);
      leds[0] = CRGB(colorValue,255,0);
    }
    if (x>=freqBounds[3] && x<freqBounds[4]){
      Serial.print("FOUR ");
      colorValue = (x - freqBounds[3]) * 255 / (freqBounds[4] - freqBounds[3]);
      leds[0] = CRGB(255,255-colorValue,0);
    }
    if (x>=freqBounds[4] && x<=freqBounds[5]){
      Serial.print("HIGH ");
      colorValue = (x - freqBounds[4]) * 255 / (freqBounds[5] - freqBounds[4]);
      leds[0] = CRGB(255,0,colorValue);
    }

    Serial.print(x,6);
    Serial.print(", ");
    Serial.println(v, 6);
  } else {
    leds[0] = CRGB(0,0,0);
  }
  for(int i = (NUM_LEDS - 1); i > 0 ; i--) {
      leds[i] = leds[i-1];
  }
  FastLED.show();
}


texts: When I open a COM port some pins on Arduino Uno goes low for about 2 seconds

texts:
I have no idea why this is happening, but after I open COM port to talk with my Arduino (I click "Open" in RealTerm), the state of some pins goes from high to low for about 2 seconds and then goes back to high. Here's my code:

void setup()
{
  pinMode(5, OUTPUT);
  digitalWrite(5, HIGH);
  Serial.begin(9600);
}

void loop()
{
}

In this case pin 5 will behave this way. I've checked it also for pin 6 and pin 8 and they behave in the same manner. I suppose more pins act like that. Why is this happening?


texts:
I wrote this code, but it doesn't work (what I want is that the program choose a random color and turn on or off an RGB led) I use transistors to turn the led strip on or off and analogWrite(pin, random(0, 255) doesn't work
int red = 11;
int green = 10;
int blue = 9;

int color = 1;
int stat = 1;

void setup() {
pinMode(red, OUTPUT);
pinMode(green, OUTPUT);
pinMode(blue, OUTPUT);
}

void loop() {
  color = random(1, 3);
  stat = random(0, 1);

  if (color == 1 and stat == 0) {
    digitalWrite(red, LOW);
  }

  if (color == 1 and stat == 1) {
    digitalWrite(red, HIGH);
  }

  if (color == 2 and stat == 0) {
    digitalWrite(green, LOW);
  }

  if (color == 2 and stat == 1) {
    digitalWrite(green, HIGH);
  }

  if (color == 3 and stat == 0) {
    digitalWrite(blue, LOW);
  }

  if (color == 3 and stat == 1) {
    digitalWrite(blue, HIGH);
  }

  delay(1000);

}


texts: How to filter or eliminate earths magnetic field readings around 3D Magnetic sensor?

texts:
Im using the SparkFun MAG3110 3D sensor:
https://www.sparkfun.com/products/12670

My application is essentially to make a contactless "magnetic joystick" using a local magnet for accurate and constant 3D position sensing in x, y, x planes of a local magnet, exactly like in this video (skip to 1:06):
https://www.youtube.com/watch?v=CO6y6bjFfmY

The magnet I'm using is constant, so i'm trying to figure out a way to remove the earths magnetic field noise around the sensor so it cannot interfere with the sensors readings as if the earths magnetic field was virtually not present.

I've already written code that takes about 50 samples in each plane (x,y,z) and takes the average of each of the planes and outputs those readings minus the average offset values (Ex: Serial.print(x-xavg), Serial.print(y-yavg), Serial.print(z-zavg)). I did this to basically "zero out" the earths magnetic field, like zeroing a weight scale.

That wasn't really effective and results were not anywhere near constant after introducing and removing the local magnet, over and over again.

I've considered:

a low pass filter
sensor fusion using my gyroscope/accelerometer module
(I know that sensor fusion is usually used to calibrate the Magnometer to be a more accurate compass, but is there anyway to use this technique to  eliminate the earths magnetic field?)
using data from http://www.magnetic-declination.com/ to tie into my calculations to offset the readings
Using an electromagnet module to output the earths magnetic field inverted continuously in an attempt to cancel out the earths magnetic field
trying to find a whole new sensor completely that does not have a low enough sensitivity to even detect earths magnetic field

So my questions are:

Is there any way to do this?
Are any of my considerations practical or possible?
Are there even any 3d magnetic sensors on the market that do NOT pick up the earths magnetic field? - I've contacted SparkFun, Arrow, ST, and other companies about this exact question and never really get a sure answer on this question specifically?
if not, how was this man in the video able to reduce noise around his sensor? - He shows visually that his sensor is starting to filter out noise, saying that he's using an "adaptive averages" algorithm and links to some code, but I was unable to see/find that and don't understand how he is doing that?


texts:
I'm trying to read the status of a PushButton with python via pyserial.

In the loop function of Arduino Uno I have this:

void loop() {

if(digitalRead(BUTTON) == HIGH){
Serial.print("E\n");
while(1){}
}

So, if my pushbutton is pressed, it will send this message "E" via serial and then it will enter in an infinite loop so that nothing else happens.

But I want to detect this message in the python code. So this is my python code:

import serial
import time

try:
   arduino = serial.Serial('/dev/ttyACM0', 9600)
except:
   print "Failed to connect on /dev/ttyACM0"

try:
   print arduino.readline()

   while True:
      if arduino.readline() == 'E':
        print("Detected!\n")

except:
   print ("Failed to read!")

The first print before the infinite While is working: it is printing in the ubuntu terminal "Program Initiated", which is a message that I'm sending in the void Setup function of Arduino.

Then, it gets stucked in the line:

 if arduino.readline() == 'E':

I mean, I press several times my pushbutton, and nothing is happening.

Any help?
Thanks!


texts: String generator not working as expected

texts:
I'm trying to build a random string, save it to EEPROM as int, then read it back and output it.
If I give it a predefined string then it works fine. But Something is wrong with the random string generator.

  String output;
  char letter;

  String mystr=""; //"ABCabc123..";
  String characters = "ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz";
  String numbers = "0123456789";
  String other = "<>!.,()?|=&%¤#";

  // add random characters to empty string
  for(int i=0 ; i < 12 ; i++){
    mystr += characters[random(0, characters.length())];
  }
  // add two numbers, one other and two more characters
  mystr += numbers[random(0, numbers.length())];
  mystr += numbers[random(0, numbers.length())];
  mystr += other[random(0, other.length())];
  mystr += characters[random(0, characters.length())];
  mystr += characters[random(0, characters.length())];

  // loop the string and place one character in each EEPROM address
  for(int i=0 ; i < mystr.length() ; i++)
  {
    EEPROM.writeInt( i,mystr[i] );
  }

  // read the string back from EEPROM
  for(int i=0 ; i < 17 ; i++){
    letter = EEPROM.readInt(i);
    output += letter;
  }

If I run the code output will be "H". Every time.
If I use the predefined string "ABCabc123.." then it works correct.

What am I doing wrong with building the mystr?


texts:
I am trying to communicate between my PC and Arduino Mega 2560 using this serial library. It works reliably, however I am having trouble passing messages at a high rate over serial. I set the baud to 460800 bps on both systems, and am using a serial handshake. The Arduino reads the values by parsing a string, however during my testing I cannot parse more than ~240 messages per second. Each message into the Arduino is either of the form "r/n" to reset some variables or "0,0,0\n" where in this case the zeroes are the ints I want to parse, these can change. My Arduino code in the loop is as follows:

if(Serial.available() > 0){
  resultString = Serial.readStringUntil('\n');
  if(resultString.equals("r")){
    countEnc0 = 0;
    countEnc1 = 0;
    countEnc2 = 0;
  }else{
    int counter = 0;
    int lastIndex = 0;
    for (int i = 0; i < resultString.length(); i++) {
      // Loop through each character and check if it's a comma
      if (resultString.substring(i, i+1) == ",") {
        // Grab the piece from the last index up to the current position and store it
        write[counter] = resultString.substring(lastIndex, i).toInt();
        // Update the last position and add 1, so it starts from the next character
        lastIndex = i + 1;
        // Increase the position in the array that we store into
        counter++;
      }
      // If we're at the end of the string (no more commas to stop us)
      if (i == resultString.length() - 1) {
        // Grab the last part of the string from the lastIndex to the end
        write[counter] = resultString.substring(lastIndex, i+1).toInt();
      }
    }
    analogWrite(8, write[0]);
    analogWrite(9, write[1]);
    analogWrite(10, write[2]);
  }
  Serial.println(String(countEnc0) + "," + String(countEnc1) + "," + String(countEnc2));
}

I know there are more efficient ways to parse this, however my attempts to use them yield similar results (Using parseInt(), char*, etc). Additionally, I am using 3 interrupts to read sensor values and store them in variables here, and writing the values I acquire to the PWM. As long as I can read and send up to 1000 messages per second that's all I need for now. Many thanks...been banging my head against the wall on this one.


texts: Reading Analog values of bluetooth module HC 05

texts: I am working on a project which requires signal strength of a bluetooth TX and RX. what i assume is that in bluetooth module like hc05, there is an antenna receiver which reads the analog signal and then passes it to its ADC to get data in terms of 0's and 1's. But is there any way i can read the analog signal strength of the reveiver antenna directly? Please help


texts: Bluetooth: sync time from an NTP server via Internet connection shared with Android phone

texts: I saw that it is possible to sync time from an NTP server over WiFi. I have the HC-06 Bluetooth module and an Android phone that can share its Internet connection with Arduino via Bluetooth. Would it be possible to sync time/date using this infrastructure? And if yes - how (which libraries, etc..)? Has anybody done it already and there is a tutorial on that?


texts: Typedef not accepted as a data type in a function?

texts:
I know I'm in a C++ compiler, but I typically create a typedef from structures, probably a holdover from earlier C programming. So this has my head spinning. I create a Typedef from a structure. After that, I have no trouble declaring a global or local version of that structure anywhere in a function, or outside of all functions (global). But when I try to create a function with this typedef as an arg, or even a function arg with a pointer the such a typedef, the compiler complains (and the complaint doesn't seem to make sense). Example...

typedef struct ss_tag {
  uint16_t settingsSavedCount;
  uint16_t codeID;

// a few more vars

  uint8_t powerDownSaveFlag;       // lets me know why we're being reset.
  uint8_t future[10];
} Sunstates;

So now, this typedef seems as good as any other. Either of these statements compile fine...

Sunstates sunStates;
Sunstates * pSS = &sunStates;

But if I now try to create a function, with either an instance of this data type or a pointer to it, like so...

void systemDataVerify(Sunstates *pST) {  }

The compiler arduino compiler offers this confusing error message...

  Arduino: 1.8.3 (Windows XP), Board: "Arduino Nano, ATmega328"

  SolarControler_21a:393: error: variable or field 'systemDataVerify'
  declared void

  void systemDataVerify(Sunstates *pSS) { }

                   ^

  SolarControler_21a:393: error: 'Sunstates' was not declared in this
  scope

  SolarControler_21a:393: error: 'pSS' was not declared in this scope

  void systemDataVerify(Sunstates *pSS) { }

  exit status 1 variable or field 'systemDataVerify' declared void

The fact that it doesn't like me declaring a function void is odd, but not as troubling as it calling my function a 'variable or field' and definitely not as strange as it saying my datatype (Sunstates) was NOT"declared in this scope. The data type was defined immediately before the function.. and the fact I could declare both instances of the type AND pointers to it kind of proves it exists within the scope. Can someone help me understand why the compiler is complaining?

Edit... I was asked to include a short sketch that shows the problem...

uint8_t somefunction()
{
  return;
}

// define structure to hold/save setup and mode info

typedef struct ss_tag {
  uint16_t settingsSavedCount;
  uint8_t powerDownSaveFlag;       // lets me know why we're being reset.
} Sunstates;

Sunstates sunStates;    // creat an instance

// create a function to accept a pointer to
// type Sunstates as an arg

void systemDataVerify(Sunstates *p)
{
return;
}

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

}

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

Now... I have discovered that if I remove the 'somefunction()' definition before the Structure definition, the problem goes away. And I'm using Arduino 1.8.3 to compile this.


texts:
I am attempting to implement a light sleep mode on an esp8266 (feather huzzah) which, when a button is pressed, wakes the system up so that it can continue its normal task.

I cobbled together some code from this post, which I've slightly modified:

#include <ESP8266WiFi.h>
#include <WiFiUdp.h>
#define WAKE_PIN 5

extern "C" {
    #include "gpio.h"
}

extern "C" {
    #include "user_interface.h"
}

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

    pinMode(WAKE_PIN, INPUT_PULLUP);
    gpio_init(); // Init GPIO pins
}

void loop(){
    Serial.println("Do something...");
    Serial.println(digitalRead(WAKE_PIN));
    delay(500); //random delay for that stuff to be done

    if(!digitalRead(WAKE_PIN)){ //if we don't detect pin, sleep
        sleep();
    }
    delay(1000);

}

void sleep(){
    Serial.println("Going to sleep...");
    delay(10);
    wifi_fpm_set_sleep_type(LIGHT_SLEEP_T); // set sleep type
    gpio_pin_wakeup_enable(GPIO_ID_PIN(WAKE_PIN), GPIO_PIN_INTR_LOLEVEL);  //LO OR HI?
    wifi_fpm_open(); // Enables force sleep
    wifi_fpm_do_sleep(5000); //Sleep for short time
    delay(100);
    Serial.println("Woke up!");
}

Here is how I have things wired:

So the setup function works as expected, as well as "do something". The button reads high (1) when it is unpressed, and when I push it, it reads low (0) - which sends the ESP to sleep. In the serial monitor, I see:

Going to sleep...
Soft WDT reset

ctx: cont
sp: 3ffef7a0 end: 3ffef9a0 offset: 01b0

>>>stack>>>
3ffef950:  0001260d 00000600 3ffee970 4021fc84
3ffef960:  00001388 402020ba 402020b1 402020a1
3ffef970:  00000000 00000000 3ffee944 40202115
3ffef980:  3fffdad0 00000000 3ffee968 402027d4
3ffef990:  feefeffe feefeffe 3ffee980 40100710
<<<stack<<<

 ets Jan  8 2013,rst cause:2, boot mode:(1,6)

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

wdt reset

I'm not very experienced with Arduino or Electric Engineering, so I'm not exactly sure what is happening vs. what should happen, but this is my interpretation:

I read somewhere that reset causes are as follows:

reset causes:
    0:
    1: normal boot
    2: reset pin
    3: software reset
    4: watchdog reset

boot device:
    0:
    1: ram
    3: flash

In which case, if soft reset is considered light sleep for the esp, then the rst cause:2 is expected behavior, as it means it was triggered by pin 5. The rst cause: 4 i'm not sure about though - watchdog reset. Seems to be a protective mechanism for the device, in which case maybe the reset of this must coincide with the reset triggered by sleep mode and is normal? Or does it indicate a crash? In any case, I have no idea what all the stack stuff is, but the system does not restart - I cannot get any further readings from the serial monitor after this.

I'm not sure whether GPIO_PIN_INTR_LOLEVEL should be high or low - I couldn't find documentation on this (though I did see it in the [GPIO header source file] on git.5

I read something where someone else had a similar problem and someone made a reference to adding resistors and making sure GPIO 0 should be high, and 15 should be low. The link they posted was dead, but it made me think of something I read about deep sleep, in which you have to wire RST to 0. I actually tried running a wire between RST and holding to the #0 pad that's right by the USB port on the feather huzzah, and after that, the code would actually go to sleep, then wake itself up automatically and resume the normal loop function - but what I want is for only the button to wake up the ESP.

I'm stuck from here. Anyone have any ideas of what might be happening and how to fix it?


texts: Alternative distance-meter, HC-SR04 doesn't work very well

texts:
On door to my room there is HC-SR04 that triggers led-wave. The shorter the distance, the faster the led-wave (8 leds).

The circuit works fine in synthetic tests – moving hand or flat object towards the sensor generates gradually accelerating wave.

However, when placed on door to detect approaching persons it generates short correct (<=170 cm) impulses and the wave starts and immediately stops, again starts, etc. I guess HC-SR04 isn't good enough to detect people.

Are there any alternatives to this sensor that will correctly detect human approaching?


texts: How to power Arduino pro mini and DFPlayer mini togather with 3.7 V LiPo battery?

texts:
I made a small box containing Arduino Pro Mini , DFPlayer Mini player and a 3.7V LiPo battery. Is it possible to power two devices with 3.7 V Battery?
What is the best way to save power for longer time performance?


texts: Arduino Uno R3 stuck in DFU mode/Port not recognized

texts:
I have an Arduino Uno R3 that is simultaneously stuck in DFU mode and won't be recognized as a port in the Arduino IDE on my Macbook Pro (El Capitan). Upon receiving power, the Arduino is automatically in DFU mode (I can use dfu-programmer via Terminal to access it, even though the Arduino is not 'recognized'), and by using the process normally reserved for entering DFU mode (connecting the two pins on the left side of the ICSP) the Arduino actually exits DFU mode. However, by neither entering or exiting DFU mode, the Arduino is still not 'recognized' as a port by the Arduino IDE. Prior to this happening, I had been attempting to flash files to the bootloader with success (I got this same predicament in that process previously once, but I do not know what happened differently).

Thanks,
wblegoboy


texts:
In the Arduino Tutorial Page named "Hello World" aimed to help people connect a 16x2 LCD Display compatible with Hitachi HD44780 driver to an Arduino Uno. The pins used to connect the Arduino Uno and LCD Module are as follows:

LCD RS pin to digital pin 12
LCD Enable pin to digital pin 11
LCD D4 pin to digital pin 5
LCD D5 pin to digital pin 4
LCD D6 pin to digital pin 3
LCD D7 pin to digital pin 2

Pins 3,5 and 11 are connected to PWM Pins, however, I'm wondering if they actually need these PWM capabilities or does this tutorial just pick random pins and the LCD's D6, D4 and Enable pins doesn't actually need the PWM capabilities available of these pins.

I'm asking this as I'm considering on using an Arduino Mega for my next project and it would be much easier and neater for all the pins of the LCD to go onto the digital pins instead of some being on the digital and others on the PWM pins.


texts:
I've been using Python for quite long, and I was wondering if it can be used as a programming language for Arduino, rather than C/C++.

When I'm using the Arduino IDE, the sketch is compiled into a hex file that contains the program binary.

Knowing that micro controllers execute only binary, I would like to know if there is a tool to convert Python code into binary, so that I can upload it directly to Arduino using AVR or other programmers.

I read about Micro Python, a lightweight adaptation of Python that can fit in boards, but can only work with PyBoard, which I have never used yet.

I believe that Arduino manufacturers should start developing boards that can run Python, because it's very simple to use, unlike C/C++. It also has a lot of builtin modules that can make development very easy, which will achieve a remarkable progress in IOT.


texts:
I am assuming millis() is a Timer ISR function.
If so :
When using millis() as mentioned in Arduino Reference :
unsigned long currentMillis = millis();
What would happen if the ISR asynchronously changes the value being read in a function. I mean if I have read one byte into currentMillis, but millis had changed the value before the remaining 7 bytes are read.
Cheers and TIA


texts: Difficulty connecting arduino ethernet with PC using a switch

texts:
Facing difficulty connecting arduino ethernet(w5100) with PC using a switch (Dlink). When both are connected directly(p2p) using ethernet cable, arduino device can be pinged. However, when connected via switch - ping doesn't work, and both devices can't communicate with each other; updated the MAC addr. several times, nothing worked. How can this be resolved?

The same setup works when connected via a router instead of switch. But we need it to work with switch only.

Static ip has been assigned to both PC and arduino uno ethernet shield.


texts: Communication via IP adress with Arduino IDE and ESP8266

texts:
I have two Arduino boards and two ESP8266 modules with the NodeMCU firmware, and I want to make this:
One Aruino will be connected to one module and a vibration sensor, and when this sensor detects some vibration, it will send some data using the ESP8266 module as a server, then, the other Arduino will recieve the data with the other ESP module and display a message to a LCD screen.

I've already programmed the WiFi modules as a server and as a client using NodeMCU firmware and LuaUploader. The issue I have is that I don't know how to make a program in the Arduino IDE that communicate both Arduino boards using the ip adress assigned to both ESP modules, can you help me? Thanks


texts: exit status 1 'mySerial' does not name a type

texts:
I just can't make it work for some reason. I tried #include <SoftwareSerial.h> and I tried #include "SoftwareSerial.h". Can someone help me?

#include <SoftwareSerial.h>

SoftwareSerial mySerial(10, 11);

uint16_t buf[256];

void setup() {
  Serial.begin(9600);
  while(!Serial);
  for(int i = 0; i < 256; i++)
    buf[i] = (uint16_t)i;
}
  mySerial.begin(4800);
  mySerial.println("Hello, world"); //printLn  L, not I

void loop() {
  Serial.write((uint8_t*)buf, 512);
  if (Serial.available()) {
    mySerial.write(Serial.read());
  }
}


texts: What is the purpose of the I/O pin capacitor on the AVR microcontroller?

texts: What is the purpose of the capacitor on the I/O pins on the ATmega328 (I imagine it's on other AVR microcontrollers as well)? Is it to reduce noise from other parts of the microcontroller?


texts: Looking for hardware - 3.5" TFT with capacitive touch

texts:
I'm looking for a 3.5" display (480x320) with a capacitive touch attached. Anyone have some experiences? I want to drive the display with 8bit.
If there are existing libraries that would be highly appreciated.

Cheers
jb


texts: Clicking a mouse based on dwell time / how to code a rolling total of sensor measurements

texts:
I'm trying to write code that should result in a click of the mouse, based on dwell time. I'm getting data from a gyroscope to move the mouse around. I'm not sure what the best way is to approach this from a coding perspective.
My current thinking in pseudocode is below. Basically it should be a rolling total of the last X sensor measurements, which is then compared to a dwell size/radius variable.
On a high level, what would be a feasible approach? I tried a couple of times with for loops and different code, but didn't get anywhere close. I would really appreciate advice about whether my high-level approach is even feasible. Thank you!
update array with sensor measurements for (i =  dwell time) ();
    update sum of the array = + i measurement; - (i - size of the array) measurement at each sensor measurement
if at last element of array
    if sum of the array < dwell radius; click
    loop to the beginning of the array

Though I'm not sure if (i - size of the array) measurement is even possible to do, since it could result in negative i values.


texts: How to upload a sketch to an atmega328 via FTDI FT232RL UART and Arduino IDE?

texts:
I have a sparkfun AVR Pocket Programmer and have burned the bootloader and uploaded programs using "upload using programmer" via USBtinyISP. It works fantastic.
I have a sparkfun FTDI Basic (as well as another FTDI breakout) that can send and receive bytes via the Arduino IDE serial monitor.
However, I cannot upload a new sketch or modified sketch to the atmega328 via FTDI. The IDE just hangs at the upload till timeout. Here is the list of some of my troubleshooting attempts:

I have tried uploading a plain bootloader, as well as a running program via the ISP programmer before attempting the FTDI.
I have tried direct connecting the FTDI DTR/RTS reset to the Atmega328 pin1.
I have also tried connecting the FTDI DTR/RTS reset to a one side of a 0.1uF cap, and the other side of the cap to the Atmega328 pin1. I assume the cap is to send just a reset pulse instead of a reset constant.
I have tried a different brand of FTDI FT232RL chip. No difference.
I have tried adding 1k resistors on the Tx and Rx lines. No difference.

Being able to program over serial is really the secret sauce that makes Arduino so much easier for beginners than a stock AVR chip. However, I have not been able to locate any detailed information on how this Arduino programming via serial really works. Also, I am not sure how the reset pin works in relation to this process. I remember something that on old Arduino boards you had to press or hold the reset when uploading, but have not be able to find any of this information either as it has been buried by time.
This Building an Arduino on a Breadboard Article and photo from that article below is a good outline of the setup I have right now. But in this configuration it seems that a sketch can not be uploaded. What do I need to add breadboard circuit in order to upload a sketch via serial? Or what procedure do I need to do with the reset button when uploading?

Thanks!
Atmega328 Spec Sheet PDF


texts:
I have got this LCD screen

I'd like to be able to decide every pixel status of the screen. Do I need to work directly with the buffer or is there another method?


texts: Streaming integer data from Arduino to Java, integer greater than 0xFF

texts:
I need to send how many milliseconds elapsed since the beginning of the time the arduino runs to java using Serial.write(). However, the largest integer that I can throw in there is 255, naturally since the largest 1 byte value we can send is 0xFF.
But if we have an integer like 6000 miliseconds that I want to send into java, how can I do this? I was initially thinking of just checking if the number is greater than 255 then bit shift it by 4 to the left then doing number<<4 & 0xFF00 and also writing (number<<4)>>8 &0xFF
But

that doesn't work for numbers really large and
I believe when I stream these int values into Java they get read as characters...

how do I fix this?
EDIT
I've created a second version as the following
void sendData(int a ){
  while(a>0){
    Serial.write(a&255);
    a = a>>8;
  }
}

on the java side I have to somehow multiply the correct x for 16^(x) to the value that we receive since everything is received backwards I'm not sure if this is the best way to go since we don't necessarily know how many bytes that we'll receive


texts:
I buy an ESP-10 module and I want to upload custom room to its flash. The problem is that there is no way to access GPIO 0 pin! Is there some way around it to upload custom room without connecting GPIO 0 to the ground?
How in the earth should I program it without this pin?
here is an address to supplier's page which contains schematic and some other details.
https://www.tindie.com/products/George/esp8266-esp-10-module/#product-description


texts:
I have a piece of code I'd like to make Arduino editor friendly. The code is written in C and contains macros the Arduino IDE can't deal with. Is it a good idea to turn those macros into functions?

#define AN221_EXECUTE_Low   cbi(PORTA, PIN0)        //drive EXECUTE low
#define AN221_PORb_High     sbi(PORTA, PIN1)        //drive PORb high
#define AN221_ACTIVATE      bit_is_set(PINA, PIN2)      //sense ACTIVATE high
#define AN221_NO_ERROR      bit_is_set(PINA, PIN3)      //sense ERRb high i.e. no rror
#define AN221_ERRb_Input    outp(0xEB, DDRA)        //make uP drive ERRb
#define AN221_ERRb_Output   outp(0xE3, DDRA)        //make uP sense ERRb


texts: Voltage changes but digitalRead always HIGH

texts:
I developed simple push button project
I used wemos D1 mini
I connected D3 pin to pull down 1K resistor.

I used multimeter to measure D3 pin voltage.

When i push the button, D3 pin voltage changes from 0.x volt to 4.x volt

But digital read on D3 always return HIGH.

Please help me find the problem. Thanks in advance

This in my sketch :

int ledPin = D2; // choose the pin for the LED
int inPin = D3;   // choose the input pin (for a pushbutton)
int val = 0;     // variable for reading the pin status

void setup() {

  pinMode(ledPin, OUTPUT);  // declare LED as output
  pinMode(inPin, INPUT);    // declare pushbutton as input
}

void loop(){

  val = digitalRead(inPin);  // read input value
  if (val == HIGH) {
    digitalWrite(ledPin, LOW);
  } else {
    digitalWrite(ledPin, HIGH);
  }
}


texts: How can I connect the MP503 to an Arduino Uno (Smoke, Alcohol Sensor)?

texts:
I don't know how I can connect an MP503 sensor to my Arduino.

Please help.

http://eleparts.co.kr/data/design/product_file/SENSOR/gas/MP503%20(Ver1.4)%20-%20Manual.pdf


texts: Improve sampling speed while using a multiplexer

texts:
I currently connected 5 sensor via a multiplexer (I must connect them to a multiplexer because they are I2C devices but they cannot been allocate more then 2 addresses so I use a multiplexer to solve the addressing problem).

However the sample rate is a shame , it is about 6.5Hz . I wish I could improve the sample rate by using some tricks.
In my loop() function, multiplexer will loop through channel 0-4 , and read each of these channel's sensor value and print it by using Serial.print()

Is there any tricks I could use to improve my sampling rate faster ? Thanks...

Here is my multiplexer class :

class MUX {
public:
//mux control pins:
int s0 = 22;
int s1 = 24;
int s2 = 26;
int s3 = 28;

//SIG pin (not necessary WHEN sig is connect to 5V)
//int SIG_pin = 0;

//array to store channel :: muxChannel[channel numbers ][4 digit channel representation]
int muxChannel[16][4] = {
  {0, 0, 0, 0}, //channel 0
  {1, 0, 0, 0}, //channel 1
  {0, 1, 0, 0}, //channel 2
  {1, 1, 0, 0}, //channel 3
  {0, 0, 1, 0}, //channel 4
  {1, 0, 1, 0}, //channel 5
  {0, 1, 1, 0}, //channel 6
  {1, 1, 1, 0}, //channel 7
  {0, 0, 0, 1}, //channel 8
  {1, 0, 0, 1}, //channel 9
  {0, 1, 0, 1}, //channel 10
  {1, 1, 0, 1}, //channel 11
  {0, 0, 1, 1}, //channel 12
  {1, 0, 1, 1}, //channel 13
  {0, 1, 1, 1}, //channel 14
  {1, 1, 1, 1} //channel 15
};

void setupMux() {
  pinMode(s0, OUTPUT);
  pinMode(s1, OUTPUT);
  pinMode(s2, OUTPUT);
  pinMode(s3, OUTPUT);

  digitalWrite(s0, LOW);
  digitalWrite(s1, LOW);
  digitalWrite(s2, LOW);
  digitalWrite(s3, LOW);
  Serial.println(F("Multiplexer initialized"));
}

void selectChannel(int channel) {
  int controlPin[] = {s0, s1, s2, s3};
  for (int i = 0; i < 4; i++) {
    digitalWrite(controlPin[i], muxChannel[channel][i]);
  }
}


texts: Trying to flash ESP8266 with Arduino UNO

texts:
This is my first project other than some of the starter projects. I am trying to flash the firmware onto an ESP8266 wifi module using and arduino uno. It would be nice to know if anything is wrong/redundant in the picture below (I was looking at a few different diagrams to try and figure out what was right). I have found some tutorials saying that TX should go to RX instead of TX to TX so that is what I am doing. I am trying to use the level shifter to go from 5v to 3.3v because I wasn't sure if I had enough current going to the ESP8266 when just directly hooked up to 3.3v on arduino (I read in a few places that the arduino doesn't have a strong enough current to operate the wifi module). I found some tutorials which use a voltage regulator, I tried doing that but had the same results I am getting now. I have also read that you don't need a level shifter or voltage regulator but it might harm the components so I haven't tried that way yet.

I am the point where I plug it into my computer via USB, open the Arduino IDE > Tools > Serial Monitor.

I type the command 'AT' and there is no response - I tried every baud setting. Sometimes it randomly outputs a question mark or two.

Other things of note: When I plug it in, the ESP8266 blue light flashes once. When I was modding the header pins of the ESP8266 I kind of fumbled it a lot - could that have broken some aspect of the chip? Also while modding the header pins, I pushed them all in to make them longer and bent them on the other side, so it would work with the breadboard - I'm wondering if the soldering connections need to be stronger (you can kind of see in the picture).

This is the schematic for what I was trying to achieve basically, while also using the level shifter:

Any advice with regards to anything you see here would be great, I am new to the world of circuits.

Note: there is a ground wire that is not in the frame of the picture connecting one side of the breadboard to the other, that part of this is one thing I was wondering about.


texts:
I want to control about 20 leds with an arduino mega.
This leds works with 12v voltage.

I tried to put 20 relays but this solution is not good for me because leds will often blink

I have also tried transistors but it needs to make a pcb.

I am looking for a solution without having to create a pcb

Any idea ?

Thanks


texts:
Can I ping or “hello world” an Arduino.
Background:  My son and I bought a 3-D printer kit.
(EZ-3D)

We are having some issues talking with it.  (Well we can't talk at all.)  So we thought to upload the firmware,

It’s an Arduino Mega 2560, and when we upload the Arduino times out… but it takes a minute or two.  Can I try some simpler program just to try and talk to the Arduino?

I’m almost a “virgin” Arduino user so be gentle.


texts:
I am trying to get JSON data from my website using an HTTP GET request, but I'm getting a 400 bad request error. Can someone let me know why am I getting this error and how to fix that? I am tired of looking at online resources.

I am trying to fetch data from www.himalayavats.com/to_fetch/system_info.json

I am using this code:

#include <SoftwareSerial.h>

const byte rxPin = 2;
const byte txPin = 3;

SoftwareSerial ESP8266 (rxPin, txPin);

unsigned long lastTimeMillis = 0;

void setup() {
  sendData("AT+RST\r\n",1000, true);
  Serial.begin(9600);
  ESP8266.begin(9600);
  delay(2000);
  connectToWifi();
}

void connectToWifi() {
  String ssid = "moto g";
  String pass = "hvats555";
  sendData("AT+CWMODE=1\r\n", 3000, true); // Configure as client
  sendData("AT+CWJAP=\"moto g\",\"hvats555\"\r\n", 5000, true);  // Connects to wifi
}

String sendData(String command, const int timeout, boolean debug) {
  String response = "";
  ESP8266.print(command); // send the read character to ESP8266
  long int time = millis();
  while( (time+timeout) > millis() ) {
    while(ESP8266.available()) {
      // The ESP has data so display its output to serial window
      char c = ESP8266.read(); // read the next character
      response+=c;
    }
  }
  if(debug) {
    Serial.print(response);
  }
  return response;
}

void printResponse() {
  while (ESP8266.available()) {
    Serial.println(ESP8266.readStringUntil('\n'));
  }
}

void loop() {
  if (millis() - lastTimeMillis > 30000) {
    lastTimeMillis = millis();
    ESP8266.println("AT+CIPMUX=1");
    delay(1000);
    printResponse();
    ESP8266.println("AT+CIPSTART=4,\"TCP\",\"himalayavats.com\", 80");
    delay(1000);
    printResponse();
    String cmd = "GET /to_fetch/system_info.json HTTP/1.1";
    ESP8266.println("AT+CIPSEND=4," + String(cmd.length() + 4));
    delay(1000);
    ESP8266.println(cmd);
    delay(1000);
    ESP8266.println("");
  }

  if (ESP8266.available()) {
    Serial.write(ESP8266.read());
  }
}

I get this response every time:

AT+CWMODE=1

OK
AT+CWJAP="moto g","hvats555"

WIFI DISCONNECT
WIFI CONNECTED
WIFI GOT IP

OK
AT+CIPMUX=1

OK

AT+CIPSTART=4,"TCP","himalayavats.com",80

4,CONNECT

OK

AT+CIPSEND=4,43

OK
>
Recv 43 bytes

SEND OK

+IPD,4,1370:HTTP/1.1 400 Bad Request
Date: Tue, 19 Dec 2017 08:30:21 GMT
Server: Apache
Accept-Ranges: bytes
Vary: Accept-Encoding,User-Agent
Connection: close
Content-Type: text/html

My JSON file on the website looks like this:

{"power" : "high"}


texts: Arduino Pro Mini (5V) Raw Pin and VCC Pin

texts:
I am new to the microcontroller world and circuits, so bare with me. I recently bought some 5V arduino pro mini microcontrollers. I have been playing with them and they work fine, I have been powering it from an usb connection.
Now I want to power the board using a 9V battery, I connected the + to the RAW pin and the Ground to the Ground pin on the Arduino.
My question is if I can still use the VCC pins? I understand the board has a voltage regulator that from my understanding it brings down the 9V to 5V. I thought this 5 volts were available through the VCC pin but I connected an LED to it and nothing happens.

I have tried this method with an arduino Uno and it works so I dont know why it doesnt work with the Pro Mini.


texts: How to power an Arduino Nano without mini-B USB port?

texts: I'm new to Arduino. I want to power my Arduino Nano with an external DC source, not with already attached mini USB port. I tried, but fail. Please help me to understand it. Thank you.


texts: Why can I not use pointers instead of array with PROGMEM?

texts:
I'm currently changing some libraries to use flash instead of RAM for string storage so that I do not run out of SRAM on a project.

Some strings in the library are declared in this manner:

const char *testStringA = "ABC";

This is different to how I normally see this done:

const char testStringB[] = "DEF";

However, I think that these two are equivalent when declared const and initialised in the declaration. Both work fine in code.

I attempted to move these to flash:

const prog_char *testStringC PROGMEM = "GHI";

I then found that this didn't work. It was producing gobbledegook when printed.

However, following the more usual pattern of:

const prog_char testStringD[] PROGMEM = "JKL";

works fine.

I can see in the disassembly:

00000068 <testStringC>:
  68:   04 01                                               ..

0000006a <_ZL11testStringD>:
  6a:   4a 4b 4c 00                                         JKL.

So it is clear the pointer and PROGMEM results in the string/array not being initialised.

Why is this?

Example code:

#include <avr/pgmspace.h>

const int BUFFER_LEN = 20;

const char *testStringA = "ABC";
const char testStringB[] = "DEF";
const prog_char *testStringC PROGMEM = "GHI";
const prog_char testStringD[] PROGMEM = "JKL";

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

void loop()
{
    char buffer[BUFFER_LEN];

    Serial.println(testStringA);
    Serial.println(testStringB);

    strncpy_P(buffer, testStringC, BUFFER_LEN);
    Serial.println(buffer);

    strncpy_P(buffer, testStringD, BUFFER_LEN);
    Serial.println(buffer);

    delay(1000);

}


texts: Why can't I define the constant A0 (some pin) to something?

texts:
What I'm doing wrong or why is it not working:

#define Uin A0;

void setup() {
}

void loop() {
  analogRead(Uin);
}

Results in a Error (expected ')' before ; token.

I thought #define just exists as a place holder.


texts: Is the a low memory alternative to SoftwareSerial?

texts:
I'm running a program on a ATtiny85 and running into problems because of a lack of available RAM. When I ran avr-nm on my ELF file I found that SoftwareSerial was taking up a lot of RAM even though I'm just using it to set the data transfer rate with mySerial.begin(9600); and nowhere else.

So I'm wondering if there is another way of doing this without using so much memory:

#include <SoftwareSerial.h>

SoftwareSerial mySerial(0,1);

mySerial.begin(9600);


texts: how to change variable when a button connected to pin 2 is pressed

texts: Hi i am writing a code where, i have to switch a variable called toggle from 0 to 1 to 0.... every time the button is pressed (the button is on a 2 pin). I am a little lost as I am new to arduino need some help. Thank you


texts: Runtime Error when using array of structs of unknown size as variable within class - some kind of overflow issue?

texts:
I have a class defined as below, it's basically a simple ring buffer, with some methods for getting useful statistics from the data held in the buffer.

enum BalanceMsgType{
  BAL_MSG_NOT = 0,
  BAL_MSG_READING = 1,
  BAL_MSG_SPECIAL = 2,
  BAL_MSG_ERROR = 3
};

typedef struct MeasuredMass{
  float mg;
  unsigned long time;
  bool steady;
  BalanceMsgType type;
};

class RingBuffer{
  private:
  unsigned int _size = 0;
  unsigned int _pos = 0;
  MeasuredMass *_array;
  void LinearRegression(){
    //... left out for simplicity
  }
  public:
  float lin_reg_m = 0;
  float lin_reg_c = 0;
  float lin_reg_r = 0;
  float est_current_mg = 0;
  //methods
  RingBuffer(unsigned int size){
    _size = size; //forgetting to put this line ->div0-> >1hr debugging :(
    _array = new MeasuredMass[_size];
    for (int i = 0; i < _size; i++){
      _array[i].mg = 0.0;
    }
  }
  void Add(MeasuredMass in_element){
    _array[_pos] = in_element;
    _pos = (_pos + 1)%_size;
    LinearRegression();
    est_current_mg = lin_reg_m*(in_element.time+BALANCE_DELAY) + lin_reg_c;
  }
  void ReadInOrder(MeasuredMass *pdata){  //Call with
                                          //my_buffer.ReadInOrder(data)
    for(int i = 0; i < _size; i++){
      pdata[i]=_array[(_pos+i+1)%_size];
    }
  }
  float Sum(){
    //...
  }
  float Mean(){
    //...
  }
  float StdDev(){
    //...
  }
  bool SteadyEnough(float max_sd){
    //...
  }
};

It compiles fine, and runs nicely in test programs. However, if I include it in larger programs (something like progmem 117404 of 122880 bytes, global vars 13604 of 32768) I get a "Board at COM8 not available" warning when using the Arduino Serial Monitor after uploading to my Fubarino Mini. (Even without actually interacting with those programs beyond creating an instance of the class.) Recent experience tells me this is some kind of crash due to a runtime error.

Fiddling around with the code, I've found that the issue doesn't occur in a version of the library which holds an array of floats instead of my MeasuredMass. That my MeasuredMass struct is obviously much larger than a float suggests to me that this is due to some pointer/array overflowy behaviour.

I've also managed to show that if I alter the class such that it uses a fixed length array rather than a pointer to one, the issue disappears.

i.e. RingBuffer's private member MeasuredMass *_array; becomes MeasuredMass _array[25];
and

RingBuffer(unsigned int size){
  _size = size; //forgetting to put this line -> div0 -> >1hr bugtracking
  _array = new MeasuredMass[_size];
  for (int i = 0; i < _size; i++){
    _array[i].mg = 0.0;
  }
}

becomes

RingBuffer(){
  for (int i = 0; i < _size; i++){
    _array[i].mg = 0.0;
  }
}

I'd rather maintain the ability to set the size of the ring buffer at runtime (in my case it's set based upon the number of seconds' worth of data requested), so can anyone help me in figuring out how I can achieve this without running into the overflow / memory problems I seem to be having?

Thanks


texts: Variables not initialized in Class Constructor

texts:
I'm creating a library driver for AdaFruit's GFX library. During Constructor initialization, all the variables (set in another .cpp) are returned as zero. This code has several modular files to separate graphics functions from graphics primitives from device interfacing. What am I doing wrong?

In the Arduino sketch I call the class constructor: MB_GFX_SPI (in file MB_GFX_SPI.cpp).
In the Constructor I'm call a function: mbR.SetMatrixSize (in another file raster.cpp).
Also in the Constructor I call a function: clearScreen (in the same file MB_GFX_SPI.cpp).

The test variable  mbR.r_totNumChannels set in clearScreen is returned with 99.
All the variables set in mbR.SetMatrixSize return zero.

//Test Sketch
//Initialize both the Adafruit library and the current library.
//Instantiate an object mbGFX so all Adafruit GFX and MB_GFX add-on functions are addressed as mbGFX.xxx();
MB_GFX_SPI mbGFX = MB_GFX_SPI(Period, numCathodeLeds, numAnodeLeds, CathodeSSPin, AnodeSSPin);

//In file MB_GFX_SPI.cpp

MB_GFX_SPI::MB_GFX_SPI(int Period, int numCathodeLEDS, int numAnodeLEDS,
      int CathodeSSPin, int AnodeSSPin)
      : Adafruit_GFX(numCathodeLEDS, numAnodeLEDS) {

  mbR.SetMatrixSize(numCathodeLEDS, numAnodeLEDS);
  clearScreen(0);
}
void MB_GFX_SPI::clearScreen(uint16_t color) {
   mbR.r_totNumChannels = 99;   //test set value
}

//In file mb_raster.cpp

void mbRasterClass::SetMatrixSize(int numCathodeLeds, int numAnodeLeds){
//cathodes require 1 byte per channel
//anodes require 1 bit per channel

    int numAnodeChannels = numAnodeLeds;
    int numCathodeChannels = mbX.pin2pin * numCathodeLeds; //times 1 or 3

    r_numCathodeRegisters = (int)((numCathodeChannels+7)/8);   //select next higher number of registers
    r_numCathodes = 8 * r_numCathodeRegisters;  //must be whole 8 bit registers - is every single chatode pin
    r_numAnodeRegisters = (numAnodeChannels+7)/8;       //round up to next register number
    r_numAnodes = 8 * r_numAnodeRegisters; //must be whole 8 bit registers
    r_PWMBufferSize = r_totNumChannels = r_numAnodes * r_numCathodes;

    r_PWMBuffer = (uint8_t *) realloc(r_PWMBuffer, r_totNumChannels); //resize array for PWMBuffer
}


texts: Using a class instance with Wire.onReceive

texts:
Is it possible to register a class instance member function with Arduino's Wire.OnReceive?

I'm trying to make my code object-oriented, and want a specific non-static class function to handle I2C data, but if I'm reading this thread correctly, onReceive is incompatible with classes since it only accepts a function pointer, which won't store context.


texts: Library for working with a 4-digit 7-segment indicator SH5461AS

texts:
Good day. Tell me an excellent library for working with a 4-digit 7-segment indicator.
I am currently using #include <fDigitsSegtPin.h>
But it does not allow you to display letters, does not allow you to put dots in the right place.
I think it is not flexible.
I want it to be easy enough to control the indicator and have sufficient freedom to choose segments (numbers, letters, dots, dashes). I tend to use the library: "SevenSeg library".
Tell me a really good option for my goal, and so that, as always, this library does not slow down all the code
I am using an indicator of the form:


texts:
(Newbie Arduino developer).

I am interested to read the signal being sent to a small flat screen display in an industrial appliance, while not disturbing the display. The goal is to capture screenshots and upload them over a network connection.

Is that possible. What do I need to find out about the signal/display?

Any pointers to get started, would be greatly appreciated.


texts: I need a sensor (or camera) for my Arduino project with which I can track objects (or living beings). This sensor should be on a motor and move with the object. Unfortunately, I don't know which sensor is suitable for living beings. The goal is to track the object with the sensor (or camera).


texts: Servo position initiaition using PySerial unexpected results

texts:
Hi I'm using Brian Wendt's code for setting up my Arduino Nano with 4 servos using PySerial which works perfectly.

So my next step was to get a nice GUI with sliders to position the servos, again no problems.

This issue is when I try to set an initial state for the servos. Servos 1 & 2 go to 0 degrees on start up but servos 3 & 4 go to 90 degrees for some reason?

My Python code for initialization,

import serial

usbport = 'COM5'
ser = serial.Serial(usbport, 9600, timeout=1)

def init():
    for servo in range(1, 5):
        print servo
        ser.write(chr(255))
        ser.write(chr(servo))
        ser.write(chr(0))

init()

Any takers?


texts:
i need using OV7670 camera on my arduino mega, and i found this site have tutorial using ov7670 camera, but in this tutorial they use arduino Uno. if i'm using arduino Mega2560, what i need to do? do i have to change their code and pin connection ?

here is the link

https://www.instructables.com/id/OV7670-Arduino-Camera-Sensor-Module-Framecapture-T/?amp_page=true


texts:
I'm trying to get a fade to happen when an LED turns on/off during the color wipe rather than just abruptly turning on/off. I'm not quite sure how to do this though.

#include <Adafruit_NeoPixel.h>

Adafruit_NeoPixel strip = Adafruit_NeoPixel(8, 3, NEO_RGBW + NEO_KHZ800);
void setup() {
  strip.begin();
}

void loop() {
  colorWipe(strip.Color(255, 255, 255), 150); // Red
 colorWipe(strip.Color(0, 0, 0), 150); // Red
 delay(5000);
}

void colorWipe(uint32_t color, uint8_t wait) {
  for(uint16_t i=0; i<strip.numPixels(); i++) {
      strip.setPixelColor(i, color);
      strip.show();
      delay(1000);
  }
}


texts: I have a problem trying to limit motor speed to a certain RPM using a MOSFET trigger switch module

texts:
I am using the potentiometer to control the duty cycle of a PWM signal to the MOSFET trigger switch module, thus controlling the motor speed.
In my code, I have used the map function to utilize the full resolution of my potentiometer (0 - 1023) and thus create a proportional PWM signal using analogWrite function (0 - 255).
However, in my setup I want to limit the speed of the motor from going beyond a MAX_RPM value, despite any further increase in analog value input from the potentiometer.
This means I have to continously check the RPM value (the RPM code works fine, so I will not include it).
If the motor speed hits the MAX_RPM value, any further potentiometer input should be ignored. To achieve this, I figured I need to hold the analogWrite function value constant thus holding the speed constant.
In the event that I turn the potentiometer in the reverse direction, this should decrease the PWM value thus also decreasing the speed.
I have written the code to achieve the process described above to no avail i.e., increasing potentiometer input causes the speed to go beyond the MAX_RPM value which is undesired.
In this project, I am developing a rev limiter of sorts.
Please help me figure out the problem in my code.
#define MAX_RPM 500
    #define MAX_RPM_PWM_MAPPED_VALUE 15

    //In this case, I first ran the motor while monitoring the speed and the potentiometer value
    //While doing this, I noted the potentiometer value at which the MAX_RPM is obtained
    //I then defined this potentiometer value as MAX_RPM_PWM_MAPPED_VALUE
    //With MAX_RPM_PWM_MAPPED_VALUE, I would directly limit the value written to the analogWrite function
    //

    MOSFETMODULE = 4;
    potentiometer = AO;

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

    void loop()
    {
        val = analogRead(potentiometer);  //Read potentiometer value - represents accelerator input
        mappedValue = map(val, 0, 1023, 0, 255); //Map the 10 bit value to 8 bit equivalent

        if(RPM >= MAX_RPM)
        {
            analogWrite(MOSFETMODULE, MAX_RPM_PWM_MAPPED_VALUE);
        }
            else
            {
              mappedValue = constrain(mappedValue, 0, MAX_RPM_PWM_MAPPED_VALUE);
              analogWrite(MOSFETMODULE, mappedValue); //Output a PWM signal to the MOSFET trigger module
            }
    }


texts: Is it possible to send a float Array over I2c

texts:
I have tried it several times myself but i never could send or receive it properly. I am asking myself if it is possible and if so could someone explain how?

Cheers.


texts: How to break out the due power supply and USB connectors?

texts:
I am planning a build with my own enclosure for the arduino due. As an alternative i would like to bypass the power jack and usb port that are factory soldered onto the board, in order to use jacks mounted on the enclosure, along with a power switch.
I've looked at the info regarding the boards pin configuration at https://www.arduino.cc/en/pmwiki.php?n=Main/arduinoBoardDue, and would appreciate if someone could confirm or correct this:

Can i use an external 9V adapter through a jack connected to the Vin and GND pins, respectively?

According to This question, you can't connect an alternative programming USB port to Serial 0 TX/RX pins (Mega board). If this applies to the due as well, what do i need to break out the programming USB port?

Edit: Perhaps one of these puppies is the least complicated solution?


texts: What does serial data look like on an oscilloscope?

texts:
How I can find the data field on oscilloscope at 300 baud or at 9600 baud?
Could someone show me picture on oscilloscope plase.

This is the picture

at 9600 Baud


texts:
I tried to make a program that can control a 4 channel relay (with LEDs as indicators) with a serial monitor. First time I tried to program it using a char command to make it turn on only, it worked. Then I tried to make it off only, it also worked, but when I tried to combine them, to control it to On or Off in the same program, it didn't work.

this is my code

#define CH1 2
 #define CH2 3
 #define CH3 4
 #define CH4 5
  void setup(){
 Serial.begin(9600);

pinMode(CH1, OUTPUT);
pinMode(CH2, OUTPUT);
pinMode(CH3, OUTPUT);
pinMode(CH4, OUTPUT);
digitalWrite(CH1,HIGH);
digitalWrite(CH2,HIGH);
digitalWrite(CH3,HIGH);
digitalWrite(CH4,HIGH);
 }

 void loop (){
  if (Serial.available()) {

char ser = Serial.read();

 switch(ser){
 case 'on1':

 onPin1();

 break;

 case 'on2':

 onPin2();

 break;

 case'on3':

 onPin3();

 break;

 case 'on4':

 onPin4();

 break;

 case 'off1':

 offPin1();

 break;

 case 'off2':

 offPin2();

 break;

  case'off3':

 offPin3();

 break;

  case 'off4':

 offPin4();

 break;

   }

 }
 }

 void onPin1(){
    digitalWrite(CH1, LOW);
 }
  void onPin2(){
   digitalWrite(CH2, LOW);
 }
   void onPin3(){
   digitalWrite(CH3, LOW);
 }
  void onPin4(){
   digitalWrite(CH4, LOW);
 }

  void offPin1(){
   digitalWrite(CH1, HIGH);
 }
   void offPin2(){
   digitalWrite(CH2, HIGH);
 }
   void offPin3(){
   digitalWrite(CH3, HIGH);
 }
   void offPin4(){
   digitalWrite(CH4, HIGH);
 }

with that code, I got "duplicate value", maybe because the pin is double-called. But when I tried to make it in separate swicth case condition, no error but couldn't respond to the command char


texts: I'm getting an error while uploading my code to esp8266 via an arduino (FatalError('Failed to connect to %s: %s' % (self.CHIP_NAME, last_error)))

texts:
Arduino: 1.8.13 (Windows 10), Board: "Generic ESP8266 Module, 80 MHz, Flash, Legacy (new can return nullptr), All SSL ciphers (most compatible), dtr (aka nodemcu), 26 MHz, 40MHz, DOUT (compatible), 1MB (FS:64KB OTA:~470KB), 2, nonos-sdk 2.2.1+100 (190703), v2 Lower Memory, Disabled, None, Only Sketch, 115200"

Executable segment sizes:

IROM   : 228624          - code in flash         (default or ICACHE_FLASH_ATTR)

IRAM   : 26756   / 32768 - code in IRAM          (ICACHE_RAM_ATTR, ISRs...)

DATA   : 1248  )         - initialized variables (global, static) in RAM/HEAP

RODATA : 688   ) / 81920 - constants             (global, static) in RAM/HEAP

BSS    : 24880 )         - zeroed variables      (global, static) in RAM/HEAP

Sketch uses 257316 bytes (26%) of program storage space. Maximum is 958448 bytes.

Global variables use 26816 bytes (32%) of dynamic memory, leaving 55104 bytes for local variables. Maximum is 81920 bytes.

esptool.py v2.8

Serial port COM3

Connecting........_____....._____....._____....._____....._____....._____.....____Traceback (most recent call last):

  File "C:\Users\Reghunaath A A\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.7.2/tools/upload.py", line 65, in <module>

    esptool.main(cmdline)

  File "C:/Users/Reghunaath A A/AppData/Local/Arduino15/packages/esp8266/hardware/esp8266/2.7.2/tools/esptool\esptool.py", line 2890, in main

    esp.connect(args.before)

  File "C:/Users/Reghunaath A A/AppData/Local/Arduino15/packages/esp8266/hardware/esp8266/2.7.2/tools/esptool\esptool.py", line 483, in connect

    raise FatalError('Failed to connect to %s: %s' % (self.CHIP_NAME, last_error))

esptool.FatalError: Failed to connect to ESP8266: Timed out waiting for packet header

esptool.FatalError: Failed to connect to ESP8266: Timed out waiting for packet header

_

This report would have more information with
"Show verbose output during compilation"
option enabled in File -> Preferences.

I'm getting the above stated error message while I'm trying to upload a code to esp8266 via an arduino(I've removed the ATMEGA32 from my arduino). Sometimes it gets uploaded without a problem(very rarely) but mostly the upload fails.
I connected rx of arduino to rx of esp and same for tx too. 3.3v of arduino to enable and vcc of esp. graund of arduino to ground of esp and gpio0.
The code that I'm trying to upload:
void setup() {
  pinMode(LED_BUILTIN, OUTPUT);     // Initialize the LED_BUILTIN pin as an output
}

// the loop function runs over and over again forevervoid lop() {
  digitalWrite(LED_BUILTIN, LOW);   // Turn the LED on (Note that LOW is the voltage level
  // but actually the LED is on; this is because
  // it is active low on the ESP-01)
  delay(1000);                      // Wait for a second
  digitalWrite(LED_BUILTIN, HIGH);  // Turn the LED off by making the voltage HIGH
  delay(2000);                      // Wait for two seconds (to demonstrate the active low LED)
}

My settings:

EDIT: Also, I want to add one more thing when the message box says "Connecting........_____....._" during that time if i reset the esp the code starts uploading


texts: What happens if you supply too much voltage to an LED?

texts:
Say I have an LED that requires 3.5v. What happens if I power it with more voltage?

For example, my Arduino Uno has a 5v pin. If I power the 3.5v LED from the 5v pin, what will happen?


texts:
I have an Adafruit Huzzah Feather with ESP8266 board, but I think my question will apply to most all boards (as most all have an onboard regulator). Most regulators have an Enable pin (EN) as does my Adafruit board. Apparently, I can shut down the regulator by pulling this pin low. I have a specific application where an external device will provide a high signal to me when I want the device to turn on, otherwise, I want it off at all times. So, what I have is a 1k resistor pulling the EN pin low, to ground. I tried other values 10-20k but they did not pull enough low to shut down the regulator. For example, 20k pulled me down from 3.3V to 2.6V but the regulator stayed on. On the other hand, 1k pulls me down to .3V on the EN pin and this shuts it down.

Then, when the external device gives me the high signal, which I have also tied to the EN pin, this will pull it back up and turn on the regulator.

This seems to be working just fine, but I wanted to ask if this sounds reasonable (I know this is a general question but I want to know if there is a better way). A specific, related question would be am I wasting too much power by using a 1k resistor when powered up or pulled high since some of the supply current will be dumped via the 1k resistor to ground.

UPDATE: In looking at the schematic on the Adafruit site, it appears that they have pulled EN to the input via a 10k resistor. So, I am fighting that which is probably why values over 10k do not pull it down enough to turn off. If I was doing the board design, I would have reversed this and pulled EN low by default but this is not the case when using the off the shelf board. So, I guess any value below 10k should work, like 4.7k? I guess I could also remove their pull up if I wanted to get really crazy. Thoughts on all of this?

Thanks!


texts: Why does reversing the temperature sensor create heat?

texts:
I am almost completely new to Arduino and electronics, I have been following the Arduino Starter Kit and on the third project I (somewhat ironically) burnt myself touching the temperature sensor.

The circuit seemed to be perfectly fine except I had placed the TMP36 temperature sensor the wrong way and missed the step which says:

Place the TMP36 on the breadboard with the rounded part facing away
from the Arduino (the order of the pins is important!)

So, now I know well why it is important but what exactly is happening to cause this?


texts: How do I free up space on arduino Yun shield?

texts:
I recently bought arduino Yun shield, and I didnt had any external USB storage connected, I downloaded get-pip.py on Yun using wget and ran python get-pip.py which resulted in 5mb storage on yun now full and even pip is not installed.

how do I free up space or reset yun shield to original , and use USB storage as default location for storing all opkg and python onto USB storage drive ?


texts:
Is it possible to use arduino uno r3 as USB keylogger by connecting the usb male pin to CPU and keybord cable to female USB pin of arduino.
So that the keystrokes are stored in EEPROM. Without using an external storage modules or other components?

I am new to arduino, even suggestions are appreciated.

Thanks in advance.


texts: Using Arduino to show images in Serial Monitor

texts:
Some time ago I came across a Vedic in which a person has hacked an optical mouse's camera and displayed the image in the Serial Monitors.
My question:
How to use Serial Monitor to display an image captured by the Arduino


texts: Compute the size of an array that was passed as a parameter to a function

texts:
When passing an array to a function, you usually pass the length of the array along with it. You can compute the size of the array with sizeof(myArray)/sizeof(myArray[0]), which works just fine.

However, if you try to do this within the function that you pass the array to, this doesn't return the length of the array - eg. if it is an int array, it returns 1, if it is a double array, it returns 0.

Why is that so and is there any way to compute the size of an array that was passed as a parameter?


texts: How can I tell the resistance of an internal pull-up resistor?

texts:
I have a SparkFun ESP8266 Thing Dev board, to which I want to perform a digitalRead() on one of the GPIO ports. I'm using D15, and I'm configuring it for input like this

pinMode(15, INPUT_PULLUP);

It does seem to work as intended, and I am able to pull it down by connecting it to ground via a 4.7kΩ resistor.

But how do I know what the actual "correct" resistor would be? I can't find any specs for the internal pullup resistor online. On a related note, I first tried using D0, but it didn't seem to have an internal pullup resistor, since even using INPUT_PULLUP didn't turn it on.

Perhaps there are specs online and I'm just not able to find them, but is there any other way (measuring?) to find out which pins will work with INPUT_PULLUP and if so, what their internal resistance is?


texts: Arduino Attiny 85 IR library compiler error

texts:
I'm about to ask a question for the most common problem which everyone has with attiny85 and the IR library. I will try to make this question as simple as possible.

Few things about the lib and the chip

First of all the lib https://github.com/shirriff/Arduino-IRremote works great on the UNO and it's the best out there.

The Attiny85 is the smallest chip you can get able to run Arduino code. It has alot of limitations but it worth it!

The common problem

Attiny85 uses different timers from the normal Attiny and Atmega chips which makes it impossible to run the standard libraries. There are some fixes for some libs. For example the IR Remote has a version which ALMOST works with the chip and it can be found over here: http://gammon.com.au/Arduino/IRremote_Attiny.zip

However the problem lies in the core. The first time i used the patched IR i had the MIT High Low Media Group versino 1 of the core files which bearly worked but it was the first released so...

After reading this guide:http://www.instructables.com/id/Attiny-IR-library/?ALLSTEPS I used an updated core which can be found here: https://arduino-tiny.googlecode.com/files/arduino-tiny-0100-0017.zip

And the final problem

Even with the updated core i still got only 1 last error.

Compiling 'Shit' for 'ATtiny85 @ 8 MHz  (internal oscillator; BOD disabled)'
IRremoteInt.h:101: error: 'RAWBUF' was not declared in this scope
Error compiling

Does anyone know how to fix it?

Links

MIT high-low group first version: http://highlowtech.org/?p=1229
Tutorial for the chip and the IR: http://www.instructables.com/id/Attiny-IR-library/?ALLSTEPS
The IR original lib: https://github.com/shirriff/Arduino-IRremote
Updated core: https://arduino-tiny.googlecode.com/files/arduino-tiny-0100-0017.zip

Just in case you wanna know i'm using the Atmel Studio 6 with the Visual Micro plugin instead of the crappy-arduino-IDE


texts: Powering Infrared and Sonar sensors using BEC

texts:
I'm new to Arduino. I'm using Arduino Mega 2560 board & MATLAB Simulink-Arduino support package and trying to integrate Maxbotix Sonar and Sharp IR sensor for my class project. When I powered single US sensor from Arduino 5V output, the readings are fine. However, when I tried to power IR sensor in parallel with US sensor, IR readings are fine but US readings fluctuate.

So, I tried powering the sensors using BEC (5V-3A). The readings for both sensors are fluctuating(extremely noisy). From the specification mentioned by manufacturers, Maxbotix US sensor draws 2mA of current, whereas IR sensor averagely draws 20mA. Is there any way to solve this problem?

Thank you.


texts:
I'm working on command-handler library and I have a big problem with F() function.
Example sketch for library uses quite a lot of RAM, because it has to print a lot of text over UART. As before, I've used F() to lower RAM usage. It worked on first!

Lib works with help of strtok function. Command fomar is:

  cmd1,..,paramN;..;cmdN,..,paramN

Commands are separated with ; while command parameters(params) are separated with ,
Library works without any problems, it returns memory address(char*) of any command and every param.

When I try to compare parameter/command with strcmp it works only if all commands are in uppercase.
Let's take LED command for example:
It works only with Led, LED or any case where is letter d in uppercase. led won't work, and it will say that command le doesn't exist. Yes, le, it won't print led. But, after DURATION command, it somehow start working.

Memory for serial buffer is dynamicly allocaed in object constructor, in global scope.
Why? All those problems are because F(). Can someone explain why? Here's the code and screenshot of serial monitor.

void execCmd(const char *set)
{
char *cmdParam = CMDHandler.find(set, CMD_PARAM);

if (!strcmp(cmdParam, "LED"))
{
    // ONE WAY TO CHECK IF COMMAND HAS PARAM(S) - BEFORE GETTING PARAM(S) == BETTER WAY
    if (!CMDHandler.count(CMDHandler.getNext(CMD_PARAM), CMD_PARAM))
    {
        Serial.print(F("->> Command LED: Current LED status is "));
        Serial.println(digitalRead(LED_PIN));
        return;
    }

    cmdParam = CMDHandler.find(nullptr, CMD_PARAM);
    LEDStatus = 0;
    uint8_t status = atoi(cmdParam);

    digitalWrite(LED_PIN, status);
    Serial.print(F("->> Command led: LED Status is "));
    Serial.println(status, DEC);
}
else if (!strcmp(cmdParam, "LOOP"))
{
    cmdParam = CMDHandler.find(nullptr, CMD_PARAM);

    // SECOND WAY TO CHECK IF COMMAND HAS PARAM(S) - AFTER GETTING EVERY PARAM
    if (cmdParam == nullptr)
    {
        Serial.println(F("->> Command LOOP: Expected one parameter!"));
        return;
    }

    uint8_t status = atoi(cmdParam);
    if (status)
    {
        LEDStatus = 2;
        digitalWrite(LED_PIN, HIGH);
        Serial.println(F("->> Command LOOP: LED Blink Loop is on!"));
        delay(blinkDuration);
    }
    else
    {
        LEDStatus = 0;
        digitalWrite(LED_PIN, LOW);
        Serial.println(F("->> Command LOOP: LED Blink Loop is off!"));
    }
}
else if (!strcmp(cmdParam, "DURATION"))
{
    if (!CMDHandler.count(CMDHandler.getNext(CMD_PARAM), CMD_PARAM))
    {
        Serial.print(F("->> Command DURATION: Current blink duration is "));
        Serial.print(blinkDuration, DEC);
        Serial.println("ms");
        return;
    }

    cmdParam = CMDHandler.find(nullptr, CMD_PARAM);
    blinkDuration = atoi(cmdParam);

    Serial.print(F("->> Command DURATION: New blink duration is "));
    Serial.print(blinkDuration, DEC);
    Serial.println("ms!");
}
else if (!strcmp(cmdParam, "HELP"))
{
    Serial.println(F("------ HELP ------\n-> LED [0/1] - Turns off/on LED on pin 13\n-> LOOP [0/1] - Stops/starts blink loop with LED on pin 13\n-> DURATION [X] - Changes duration of LED loop blink. Recommended values is 50-500ms\n"));
}
else
{
    Serial.print(F("->> Command "));
    Serial.print(cmdParam);
    Serial.println(F(" does not exist!"));
}

}

char *CMDHand::find(const char *input, uint8_t const type)
{
    char *found = nullptr;
    char separator = delimiter[type];

    if (input != nullptr) // FIRST CALL
    {
        constrain[type] = input + strlen(input) - 1;
        next[type] = input;
    }
    else if (next[type] > constrain[type]) return (nullptr);

    found = strtok(next[type], &separator); // FOR SOME REASON IT DOES NOT WORK IF I PUT &delimiter[type] INSTEAD OF &separator
    last[type] = next[type];
    next[type] += strlen(found) + 1;

    return (found);
}


texts:
I'm new to the arduino board and my teacher gave us a project with little to no teaching about the language the board uses, or how to effectively program with it.
I'm trying to read temperature from a DHT11 and display it on two separate 7-segments displays. I've been trying to do this by editing a code he provided us that makes one display count from 0 to 9. I've been to hook up and read the DHT11 and split the temperature into two variables. But I have no idea how to make the variables display on the seven segment displays. My code is.

//DHT11 set up
#include <dht11.h>
dht11 DHT11;
void setup()
{
   DHT11.attach(4);
   for (int i = 0; i < 4; ++i)
    pinMode(i, OUTPUT);
   for (int i = 8; i < 11; ++i)
    pinMode(i, OUTPUT);
}
static int temp = DHT11.fahrenheit();
static int digit_0 = temp % 10;
static int digit_1 = temp - digit_0;
static int digit_2 = digit_1 / 10;
// Output pins.
static int output[] = {0,1,2,3};
// 8421 code lookup table.
static int segs_encoding[][4] =
  {{0,0,0,0},   //=0
    {0,0,0,1},  //=1
    {0,0,1,0},  //=2
    {0,0,1,1},  //=3
    {0,1,0,0},  //=4
    {0,1,0,1},  //=5
    {0,1,1,0},  //=6
    {0,1,1,1},  //=7
    {1,0,0,0},  //=8
    {1,0,0,1}}; //=9
// Outputs an 8421 decimal digit on the output pins from
// base to base + 3 in big endian order.
void show(int base, int num) {
 for (int i = 0; i < 4; ++i) {
   if(segs_encoding[num][i] == 1) {
     digitalWrite(base + 3 - i , HIGH);
   } else {
     digitalWrite(base + 3 - i , LOW);
   }
  }
}
// Output a 2 digit decimal value.
void show_2digit_decimal(int num) {
// force value to displayable range because show() doesn't do any sanity
  if (num < 0)
    num = 0;
  if (num > 99)
    num = 99;
  // display it.
  show(0, num%10);
  show(8, num/10);
}
void loop() {
  static int i = 0;
  show_decimal(i);
  delay(1000);
// Increases the counter.
  ++i;
  if (i == 10)
    i = 0;
}

Let me know if you guys need pictures of my breadboard set up, thanks for any help you guys can provide.


texts: 433 MHz Radio Transmitter and Reciever Range Problems

texts:
I recently started developing an interest in tinkering with my Arduino. I bought 433 MHz Transmitters and Recievers (model number: XY-MK-5V).

But when I try using them I have pratically no range: without an antenna the chips have to be nearly touching and even with an antenna I don't get even a meter of range.

Am I doing something wrong? It seems like they should have more range. I'm currently supplying them with 5V from the Arduino, because when I supplied the transmitter with 12V it would not transmit anything.

Thanks in advance
Mt_266

[
[


texts:
I want to make a device that will take a Bluetooth stream and play it on speakers via the USB port for speakers that do not have Bluetooth.

I think it may be possible by taking the stream and using an Arduino to convert the stream to a virtual file so that the speaker will see the USB as a mass storage and play the file.

I am not sure that is just an idea, any thoughts or solutions?


texts:
Since the Nano 33 boards are quite new right now, I haven't found any details on how to hook one up with batteries.

I'm pretty daft when it comes to electronics (I'm a software man), and I read that the new Nano 33 requires 3.2V, which is a bit of a departure from the 5V the old models supported.

From what I can tell, I might be able to use a single LiFePO4 cell. Am I correct in this assumption? And if so, are there any pitfalls in going this route?

EDIT: I might have misunderstood the difference between operating voltage and input voltage. Does this mean that I can plug any AA battery pack in as a power source?


texts: Only 1 DC motor spinning with motor driver l298N and arduino UNO?

texts:
So, I am making an RC Car and the problem is, that when the two motors i have should go forward, only one does, and when I turn off one motor, the other one works normally... I am powering the motor driver with  a 9V battery.

What can be the problem here? Is the current to low for them to work at the same time???