texts:
Replication Steps:

595N shift register powered by arduino
Each output on register connected to 1 of 8 relays in relay board
Arduino programmed to loop over each 8, triggering 1 relay at a time
Dedicated 5v power line connected to relay board as so
Begin loop

Expected: LED's light and relays make contact iterating over each of 8
Actual: Occasionally relay/led fires, then immediately goes out/disconnects OR occasionally relay/led x should fire, but instead relay x+1 fires

Disconnect separate DC supply from relay board

Expected: Relays will not fire/make contact, LED's will continue buggy pattern from step 5 actual.
Actual: Relays don't fire (expected), LED's light in correct order always, no bug

Friend who is more hardware savvy thinks it could be simple matter of Separate DC supply needed more voltage as my supply is providing enough amperage to fire all 8 contacts simultaneously. However, this board is rated for only 5V correct?

What gives?


texts:
I am looking to utilize Pin 13 and an external LED to flicker as either the Rx or Tx LEDs do when Serial data is transferred through the Arduino. The existing code is all in real time to function with external buttons, so there can't be any delay.

I came across this link which seems useful, but I can't quite get it to read from Serial:

http://arduino.cc/en/Tutorial/BlinkWithoutDelay

Thanks in Advance


texts: I am newbie in Arduino (using UNO) and as I have 2 components that I wish to connected that one needs 5V and the other need the 3.3V, is it safe to connected them together next to each other?


texts: analogRead function not working in MATLAB

texts:
I am new to Arduino and I am trying to control it through MATLAB.  I have downloaded the arduino IO package and installed it.I am using MATLAB 2014a.I have a LED and I change its brightness by changing the PWM voltage as follows :

a=arduino('COM3');
brightness_step = (5-0)/20;
   for i = 1:20
      writePWMVoltage(a, 11, i*brightness_step);
      val=a.analogRead(0);
      display(val)
      pause(0.1);
   end

   for i = 1:20
      writePWMVoltage(a, 11, 5-i*brightness_step);
      val=a.analogRead(0);
      display(val)
      pause(0.1);
   end
clear a

Everything works great except for the analogRead part which throws the following error :
No appropriate method, property, or field analogRead for class arduino.

What am I doing wrong?


texts:
I am a hobbyist & know little about electronics.

I am making a robot arm, like this one. For which I will need 2 stepper motors (for elbow & shoulder joint) & 4 simple DC motors.

Which means I will need to allocate a lot of pins on my board (Uno).

So I was just reading about I2C & then eventually SPI. My question is:

Is it possible to control 6 motors (or atleast 2 steppers) with I2C or SPI (assuming the motors are powered by seperate source), if so can you point me to someone's example code.
If not possible, how do I overcome the shortage of pins, because I have already dedicated them to many sensors.


texts:
My arduino mega should be communicating with another card (ANET8) and also with a DC resistance meter (with python code) using 2 serial ports, one using the USB(resistance meter) and the other one with RX and TX.
The Anet8 is sending a signal to trigger the MeasGo part in the code, and therefore with the Serial.print(A8flag) it triggers a measurment part in python, that measurement part in python sends in the Serial port a command that the arduino should read through Serial.readString and thus execute a function called "MuxRelayChoicee".
My problem is that, the part with " if Serial.available()>0 ... " is not working. I know it because my debug_pin1 is not made to HIGH.
Did i miss something ?
#include "pins.h"

#include <SoftwareSerial.h>

String flag, A8flag, sys;
int i;
int POW_RELAY_PIN=12;
int debug_pin = 38;
int debug_pin1 = 39;
SoftwareSerial mySerial(10, 11); // RX, TX

void setup() {
  // set the digital pin as output:
  pinMode(10, INPUT);
  pinMode(11, OUTPUT);
  pinMode(12, OUTPUT);

  pinMode(debug_pin, OUTPUT);
  pinMode(debug_pin1, OUTPUT);

  Set_Pins(); //to activate mux pins

    // Open serial communications and wait for port to open:
  Serial.begin(9600);
//  Serial.setTimeout(500);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB port only
  }

  mySerial.begin(9600);
//  mySerial.setTimeout(500);
  while (!mySerial) {
    ; // wait for serial port to connect. Needed for native USB port only
  }
}

void loop() {

  if (mySerial.available()>0)
  {
     delay(50);
     String A8flag ="";
     A8flag=mySerial.readString();
     delay(50);

 if(A8flag.equals("MeasGO\n")){
     Serial.print(A8flag);
     delay(100);
     Serial.flush();
     digitalWrite(debug_pin, HIGH);

     if (Serial.available()>0)
     {

        String sys ="";
        sys=Serial.readString();
        delay(50);
        digitalWrite(debug_pin1, HIGH);
        MuxRelayChoice(sys);
 }
 }

Here is a part of the code i send with python :
if flag=="MeasGO":
      for n in range(4):
        ser.write(("sys"+str(n)+"\n").encode()) #Writing to the Serial port of Arduino
        time.sleep(1)
        data=mybk.query('FETCh?')
        time.sleep(1)
        t.append(time.time()-t0)
        print("sys"+str(n)+ '\n')
        res[n]=float(data[:13])*1000
        print(str(res[n])+'\t mOhm')
      with open(path+'csvfile.csv','a') as f:
          f.write(str(time.time()-t0)[:7]+'\t'+str(res[0])+'\t'+str(res[1])+'\t'+str(res[2])+'\t'+str(res[3])+'\n') #Give your csv text here.
      time.sleep(0.5)
      ser.write("MeasOK\n".encode())


texts: Why do all analog pins measure the same value?

texts:
I measure 2 analog pins: A4 and A5. The A5 pin is connected to another Arduino's digital out (through a 10k resistor) which has a simple program: 5ms on and 100ms off. The A4 pin is not connected anywhere.

The analog pins are inited with pinMode(APIN, INPUT), reading is simply performed with the analogRead(APIN) function (there is no delay between the readings). I have tried with delays between the measurements but the results are the same.

The results:

The A5 pin (which is connected) measures the correct value. However, the unconnected A4 pin is clearly interferred by the input of A5. It works like this with another pins, delays between the readings, double use of analogRead()... I even swapped the Arduinos (Arduino Nano and Uno) and the results are the same.

Is it because of that these Arduinos are clones? Or are these Arduinos damaged?


texts:
I am having a double value for example: 34.26 or 11.92 or 2.51. It should be rounded to the nearest 0.5 so 1.34 -> 1.50 and 32.78 -> 33 and 21.09 -> 21.00

How do to do this?


texts: What happen to the counter value if I do not input the statement (if previous state!=current state)

texts:
I refer to the code from this page: http://www.toddholoubek.com/classes/pcomp/?page_id=58 :
int ledPin = 13; // choose the pin for the LED
int switchPin =2; // choose the input pin (for a pushbutton)
int val = 0; // variable for reading the pin status
int counter = 0;
int currentState = 0;
int previousState = 0;

void setup() {
  pinMode(ledPin, OUTPUT); // declare LED as output
  pinMode(switchPin, INPUT); // declare pushbutton as input
  Serial.begin(9600);
}

void loop() {
  val = digitalRead(switchPin); // read input value
  if (val == HIGH) { // check if the input is HIGH (button released)
    digitalWrite(ledPin, HIGH); // turn LED on
    currentState = 1;
  }
  else {
    digitalWrite(ledPin, LOW); // turn LED off
    currentState = 0;
  }
  if(currentState != previousState) {
    if(currentState == 1) {
      counter = counter + 1;
      Serial.println(counter);
    }
  }
  previousState = currentState;
  delay(250);
}

I do not have the Arduino device so couldn't test the result currently but am Interested to know if I omitted this line:
if(currentState != previousState)

, using the command line
if(currentState == 1) {
counter = counter + 1;

only and lets say I using a FS-V21 fiber optic sensor to count the quantity of products of 1m long each and on a conveyer belt of speed 0.1m/s so the stat will be true of t=1/0.1=10second for each product.
Will the counter value increase one unit only for each product (happen on the transition edge only), or increase indefinitely in the 10 second duration?


texts:
I am currently working on a project that makes a plateua move back and forth using a stepper motor. On this plateau I have attached LEDs that create patterns.
However, the plateau should be moving whilst the pattern is changing. With my current code this is not happening. I know that I have to work with millis, but when I am completely lost on how to do it. Could someone help me?

Here is my code:

#include <AccelStepper.h>

AccelStepper stepper(1, 42, 38);

int i;
int microStep = 46;

int currentAnimation = 0;
int count = 0;
int button = 13;

int state = LOW;
int lastState = LOW;

//bytes for patterns
byte a = B11110000;
byte b = B00010000;
byte c = B01000000;
byte e = B10100000;

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

void setup()
{
  DDRH = B1111000; // set PORT 6-9 of arduino mega high
  DDRB = B11110000; // set PORT 10-13 high

  stepper.setMaxSpeed(900.0);
  stepper.setAcceleration(400.0);

  pinMode(button, INPUT);
  state = digitalRead(button);

  pinMode(microStep, OUTPUT);
  digitalWrite(microStep, HIGH);
}

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

void loop()
{
  //This should happen constantly
  stepper.runToNewPosition(2000);
  delay(500);
  stepper.runToNewPosition(0);

  // These are the patterns, that should be played whilst the stepper is running. The patterns chaneg when you push the button
  if ( state == HIGH & lastState == LOW )
  {
    currentAnimation++;
  }

  if (currentAnimation % 3 == 0)
  {
    same();

  }
  if (currentAnimation % 3 == 1)
  {
    left();
  }
  if (currentAnimation % 3 == 2) {
    faster();
  }

  lastState = state;
  state = digitalRead(button);
}

//--------------------------------------------------------------------------------------------------------------------------------
//PATTERNS
void same() {
  for (int k = 0; k < 10; k++) //plays 10 times
  {
    PORTH = a;
    PORTB = a;
    delay(100);
    PORTH = 0;
    PORTB = 0;
    delay(100);
  }
}

void left() {
  for (int z = 0; z < 10; z++)
  {
    PORTH = e;
    PORTB = e;
    delay(100);
    PORTH = ~e;
    PORTB = ~e;
    delay(100);
  }

}

void faster() {
  for (int z = 0; z < 256; z++)
  {
    PORTH = z;
    PORTB = z;
    delay(100);
  }
  PORTH = 0;
  PORTB = 0;
}


texts: How to wire and control a 16mm button with 2 legs using arduino?

texts:
I can't find any tutorials online explaining how to wire and control a 16mm push button like the one in the picture:

Do  you have any suggestions as to how use it with an arduino or a raspberry pi?


texts: Use digital pins as analog - Arduino Micro

texts:
I have an Arduino Micro and I want to use pin 6 and 8 as an analog pin, according to the manual this is possible:

  The Micro has a total of 12 analog inputs, pins from A0 to A5 are
  labelled directly on the pins and the other ones that you can access
  in code using the constants from A6 trough A11 are shared respectively
  on digital pins 4, 6, 8, 9, 10, and 12.

What exactly do they mean by constants? I am aware what a constant is in the scope of programming, however I'm not sure what I should use to assign pins 6 and 8 as an analog pin? I assume I cannot just do an analogRead(6)?


texts:
I am having an issue with my Nextion display. I have uploaded the following code via Arduino IDE to my Arduino MEGA 2560.
My Nextion Editor shows the button as ID:9 on page0 named floor. I am not entirely sure if the code below is correct. I had one issue where the upload from the laptop to the Mega wouldn't finish, but I managed to bypass that issue by disconnecting the Nextion and swapping RX and TX cables from Nextion while the upload was in progress. Not sure how else I would fix that issue? (If anyone has any ideas haha)
All that is meant to happen is when the dual button state is changed, the onboard LED_BUILTIN is set to HIGH and if in its second state, is set to LOW.
CODE
#include "Nextion.h"

NexDSButton bt0 = NexDSButton(0, 9, "floor");

int ledPin = LED_BUILTIN;

char buffer[100] = {0};

NexTouch *nex_listen_list[] =
{
    &bt0,
    NULL
};

void bt0PopCallback(void *ptr)
{
    uint32_t dual_state;
    NexDSButton *btn = (NexDSButton *)ptr;
    dbSerialPrintln("b0PopCallback");
    dbSerialPrint("ptr=");
    dbSerialPrintln((uint32_t)ptr);
    memset(buffer, 0, sizeof(buffer));

    if(dual_state)
    {
        digitalWrite(ledPin, HIGH);
    }
    else
    {
        digitalWrite(ledPin, LOW);
    }
}

void setup(void)
{
    nexInit();

    bt0.attachPop(bt0PopCallback, &bt0);

    dbSerialPrintln("setup done");
    pinMode(ledPin, OUTPUT);
}

void loop(void)
{
    nexLoop(nex_listen_list);
}

My issue is that the MEGA is identifying the touch event (as the TX LED on the MEGA flashes) however it is not turning on the MEGA's onboard built-in LED.
Any help would be greatly appreciated!


texts: how to block Arduino code until a certain event?

texts:
i am tring to enter a series of numbers using "keypad" to different variables..when simulate the code on proteus it only took the first "getkey()" function and ignored the rest ..
SO,
How can i block an arduino code until a key is pressed by keypad, in other words prevent the rest of code from being executed before a key is pressed


texts: Can I get a Datetime object from a unix timestamp?

texts:
Is there a way to get a DateTime object from a unix timestamp and hour offset? I want to be able to print a formatted string, for example Wed Apr 02 17:15:06 2014.

I have:

A unix timestamp: 1396451852.
An offset from my hour zone, +1 hour.

Note: I get the timestamp from an internet service and want to make the conversion in the Arduino.


texts: Programming Servo How To Get -90 Degrees

texts:
as the question title states, how will I go about turning the servo opposite of 90 degrees?

I have written my code as such;

  // Turn servo to the right
  if(x > 520 && y < 510 && y > 490){
  servo.write(0);
  delay(50);

  //Turn left
  }else if(x < 490 && y < 510 && y > 490){
    servo.write(180);
    delay(50);

 //Turn backwards
} else if(y < 490 && x < 520 && x > 490){
  servo.write(-90);
  delay(50);

Obviously -90 isn't an actual degree on the servo, and it will only turn between 0 and 180. I was therefore wondering if there was any other way to code it?

The servo is connected to a joystick, and the plan is to built a 360 degrees vertical and 180 degrees horizontal turret of sorts. Every other command works, and when I replace -90 with 90 degrees, it works as well. So it is wired correctly.

Of course I would have to add another joystick and another servo later on, but at this stage I am simply testing my own coding skills.


texts: Can't send HTTP request using ESP8266 and Arduino Uno

texts:
I have an Arduino Uno and for Wifi an ESP8266.

My ESP8266 Firmware is

AT+GMR

AT version:0.40.0.0(Aug  8 2015 14:45:58)
SDK version:1.3.0
Ai-Thinker Technology Co.,Ltd.
Build:1.3.0.2 Sep 11 2015 11:48:04

baund = 115200,
 Both NL & CR

Server -- www.linysoft.com

The URL I want to send is either: http://www.linysoft.com/arduino/?light=off OR http://www.linysoft.com/arduino/?light=on.

Depending on to the link I send the result should be either ==> on or ==> off on the page http://www.linysoft.com/arduino/light.json.

Now I want to send an HTTP request (Weblink - http://www.linysoft.com/arduino/?light=on) so it can write according to that link "on" in the light.json page.

The AT command I am sending (my wifi module is connected to my wifi automatically):

WIFI CONNECTED
WIFI GOT IP

AT+CWMODE=1

OK

AT+CIPMUX=1

OK

AT+CIPSTART=0,"TCP","www.linysoft.com",80

0,CONNECT

OK

AT+CIPSEND=0,200

OK
>

Here I am getting a problem after this > I can't send **GET /arduino/?light=on**. I also tried GET /arduino/?light=on HTTP/1.0\r\n.

After putting this line in the textbox, I press the Enter button or Send Button, but nothing happens.

It is stuck here > for some time. And then it shows me:

OK
> 0,CLOSED

Pin Connection

ARDUINO UNO        ESP8266
RX  -------------->  TX
TX  --------------> RX
VCC--------------> 3.3
CH_PD ----------> 3.3
GND -------------> GND


texts: Arduino's Serial Monitor Showing Constant Value

texts:
I have a breadboard Arduino; made with ATMega328PU and a UART connector using a CT2102 breakout board. With the help of this site I created a simple IR sensor, now the problem is that in the Serial Monitor I'm getting a constant value of 1023. Even on removing the receiver (photodiode), the value's starts dropping like a capacitor discharges, and then stabilizes at some value (around 260-300).

When everything was working correctly, the value dropped to a sudden zero on removing the receiver, but now it isn't.

The "robot" was working perfectly and was reading the values correctly, but suddenly, the values dropped; we checked it and the Serial Monitor showed the same values. To check if the connections are working, I removed a wire from the Analog Pin of the Breadboard-Duino, and the values started to drop: like a periodic function.

The following code was used:

int pd=2;                      //Photodiode to digital pin 2
int buzz=13;                   //piezo buzzer to digital pin 13
int senRead=0;                 //Readings from sensor to analog pin 0  or A0
int limit=850 / 4;                 //Threshold range of an obstacle
void setup()
{
  pinMode(pd,OUTPUT);
  pinMode(buzz,OUTPUT);
  digitalWrite(pd,HIGH);       //supply 5 volts to photodiode
  digitalWrite(buzz,LOW);      //set the buzzer in off mode (initial condition)
  Serial.begin(9600);          //setting serial monitor at a default baund rate of 9600
 }
void loop()
{
  int val=analogRead(senRead) / 4;  //variable to store values from the photodiode
  Serial.println(val);          // prints the values from the sensor in serial monitor
  if(val <= limit)              //If obstacle is nearer than the Threshold range
  {
   digitalWrite(buzz,HIGH);     // Buzzer will be in ON state
   delay(20);
  }
  else if(val > limit)          //If obstacle is not in Threshold range
  {
   digitalWrite(buzz,LOW);      //Buzzer will be in OFF state
       delay(20);
  }
}

Any help will be appreciated.

EDIT

The phototransistor/diode is a standard 2pin component which came with the IR sensor.


texts: Wiring power new power button to UPS power module for raspberry pi

texts:
I have a UPS Power Module Expansion Board for Raspberry Pi 3B/3B+(Plus) and removed the power button because it is in the way and would like to attach this read button instead. But it is not working, they board does not turn on?

Am i wiring the incorrectly?


texts: How do I figure out if my board is approaching end of life?

texts: I have a uno that I have been using for 3 years now. I will be using it again in a rather critical project in which failure on the part of the board could be rather expensive and dangerous. So, I would like to be sure that the board is not approaching end of life or going to fail anytime soon. Is there any reliable way to figure out how long the board will function without failing or reduction in performance?


texts: What's the difference between #define and const int when declaring a pin?

texts:
Over the course of my Arduino usage and learning, I've noticed that in some sketches people use the #define command to declare pins, while some others simply use const int for the same.

My question is, what's the difference between the two, and which one should be preferred for use?


texts: eclipse photon with cdt-arduino plugin can't upload sketches

texts:
i've recently decided to give eclipse-photon-cdt a shot. i use it with the built in arduino plugin, downloaded my feather m0 board config and tried to upload an empty sketch. failed, the console shows it tries to connect but fails. of course arudino ide 1.8.5 succeeds wonderfully.
point is if i copy paste the command line activating bossac i get the same result. i also know why. when using scripts i need to use a python scripts that uses serial signaling to reset the feather into bootloader mode. arduino ide does it on his own probably using java. eclipse doesn't do that which sounds like a huge bug to me.

am i missing something ? or did they actually assumed i'll press twice on the reset button on the board each and every time i want to upload a sketch ?


texts:
I bought an Arduino pro micro (looks like this) from a Chinese seller over E-Bay, for its HID interface.

I installed the Arduino software on my Linux machine (Kali Linux), and started writing a USB Rubber Ducky script, and converted it to Arduino using Dckuino.js, which usually works just fine.

I may have used either:

The wrong programmer, or
The wrong board type

because when I uploaded the sketch, it said it failed, but HID script still worked when I plugged it into my Mac.

The Mac came up with a Keyboard Assistant, because it couldn't recognize the keyboard being use. So I plugged it back into my Linux machine, and it wouldn't recognize.

lsusb and dmesg -w didn't show any updates when re-plugging the Arduino.
Changing USB chords didn't work.
Switching over to windows, Device Manager didn't do the normal "refresh" when you plug in a new device, and there was nothing under COM Ports.
The HID input didn't work on the Mac anymore, when plugging it in again.
The inbuilt LED lights up when connected.

Is this a brick?
I can't seem to find any reset button or header on the board, so I cant connect the ground and reset.
There is an RST header, but I don't know what that is.

Any help would be greatly appreciated!


texts: Serial question : Going from Mega to Uno

texts:
I have a code sample that uses serial3 (RX3 on a Mega) which I want to try and get working on a Uno.  It reads on RX3 and streams to USB.  What I had read, you use Serial for RX0, however Serial seems to be used for USB

 /*
Arduino Neato XV-11 Laser Distance Scanner
Motor control board v0.2 by Cheng-Lung Lee

XV-11 LDS adapter reads LDS data from RX3 then relay to TX. Also extract the speed
data from the data stream to do speed control on LDS motor. Everythin can power
from USB no extra power required.

Change log:
V0.2 Add simple speed control code update PWM 3 times per rev.
V0.1 Opend loop control version.

This code is tested on Arduino Mega 1280
I/O:
Motor drive by low side driver IPS041L connect to PWM Pin4, Motor power from 5V
Neato XV-11 LDS Vcc(red) : 5V
Neato XV-11 LDS TX(Orange) : RX3

 */

const int DesiredRPM=300;  // Setting Desired RPM Here.
const int MotorPWMPin=4;
int inByte = 0;         // incoming serial byte
unsigned char Data_status=0;
unsigned char Data_4deg_index=0;
unsigned char Data_loop_index=0;
unsigned char SpeedRPHhighbyte=0; //
unsigned char SpeedRPHLowbyte=0;

int SpeedRPH=0;
const unsigned char PWM4dutyMax=255;
const unsigned char PWM4dutyMin=100;
unsigned char PWM4duty=PWM4dutyMin;  // have to set a default value make motor start spining

 void setup() {
    pinMode(MotorPWMPin, OUTPUT);
    Serial.begin(115200);  // USB serial
    Serial3.begin(115200);  // XV-11 LDS data

  // prints title with ending line break
  Serial.println("Arduino Neato XV-11 Motor control board v0.1 by Cheng-Lung Lee");

  // Pick your magic number and drive your motor , 178 is 178/255*5V=3.49V
    analogWrite(MotorPWMPin, PWM4duty );
}

void loop() {
    // if we get a valid byte from LDS, read it and send it to USB-serial
  if (Serial3.available() > 0) {
    // get incoming byte:
    inByte = Serial3.read();
    //Serial.print(inByte, BYTE);
    //Serial.write(inByte);
    Serial.print((char)inByte);
    decodeData(inByte);
  }

}

void decodeData(unsigned char inByte){
  switch (Data_status){
  case 0: // no header
  if (inByte==0xFA)
  {
    Data_status=1;
    Data_loop_index=1;
  }
    break;
  case 1: // Find 2nd FA
    if (Data_loop_index==22){
      if (inByte==0xFA)
      {
        Data_status=2;
        Data_loop_index=1;
      }
      else // if not FA search again
      Data_status=0;
    }
    else{
      Data_loop_index++;
    }
    break;
  case 2: // Read data out

     if (Data_loop_index==22){
      if (inByte==0xFA)
      {
        Data_loop_index=1;
      }
      else // if not FA search again
      Data_status=0;
    }
    else{
      readData(inByte);
      Data_loop_index++;
    }
    break;
  }

}
void readData(unsigned char inByte){
  switch (Data_loop_index){
    case 1: // 4 degree index
    Data_4deg_index=inByte-0xA0;
//      Serial.print(Data_4deg_index, HEX);
//      Serial.print(": ");
    break;
    case 2: // Speed in RPH low byte
    SpeedRPHLowbyte=inByte;
    break;
    case 3: // Speed in RPH high byte
    SpeedRPHhighbyte=inByte;
    SpeedRPH=(SpeedRPHhighbyte<<8)|SpeedRPHLowbyte;

    SpeedControl ( DesiredRPM ) ; //
//      Serial.print(SpeedRPHhighbyte, HEX);
//      Serial.println(SpeedRPHLowbyte, HEX);
    break;
    default: // others do checksum
        break;
  }
}

// Very simple speed control
void SpeedControl ( int RPMinput)
{
 if (Data_4deg_index%30==0) {  // I only do 3 updat I feel it is good enough for now
  if (SpeedRPH<RPMinput*60)
     if (PWM4duty<PWM4dutyMax) PWM4duty++; // limit the max PWM make sure it don't overflow and make LDS stop working
  if (SpeedRPH>RPMinput*60)
     if(PWM4duty>PWM4dutyMin) PWM4duty--;  //Have to limit the lowest pwm keep motor running
  }
  analogWrite(MotorPWMPin, PWM4duty ); // update value
}


texts:
I am trying to send the temperatures from an DS18B20 to ThingSpeak, using an ESP8266. You can see the code I am using for that.

When I run the code I do not get any errors. In serial monitor it just shows that it is not connected to WiFi. If I change the WiFi name in code to something not even existing I still do not get any errors. I do not think that the ESP even finds the WiFi.

I think that the only problem to get everything work is just to get the WiFi connection to work properly. I have also checked the ESP with another simple code just to check that it is not broken and it actually get the code from my computer.

Here is the code I am using. (I have removed my password etc... )

//nodeMCU v1.0 (black) with Arduino IDE
//stream temperature data DS18B20 with 1wire on ESP8266 ESP12-E (nodeMCU v1.0)
//shin-ajaran.blogspot.com
//nodemcu pinout https://github.com/esp8266/Arduino/issues/584
#include <ESP8266WiFi.h>
#include <DallasTemperature.h>
#include <OneWire.h>

//Def
#define myPeriodic 15 //in sec | Thingspeak pub is 15sec
#define ONE_WIRE_BUS D4  // DS18B20 on arduino pin2 corresponds to D4 on physical board
//#define mySSR 0  // Solid State Relay on pin 0

OneWire oneWire(ONE_WIRE_BUS);
DallasTemperature DS18B20(&oneWire);
float prevTemp = 0;
const char* server = "api.thingspeak.com";
String apiKey ="******";
const char* MY_SSID = "******";
const char* MY_PWD = "******";
int sent = 0;

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

void loop() {
    float temp;
    //char buffer[10];
    //DS18B20.requestTemperatures();
    //temp = DS18B20.getTempCByIndex(0);
    temp=1111;
    //String tempC = dtostrf(temp, 4, 1, buffer);//handled in sendTemp()
    Serial.print(String(sent)+" Temperature: ");
    Serial.println(temp);

    //if (temp != prevTemp)
    //{
    //  sendTeperatureTS(temp);
    //  prevTemp = temp;
    //}

    sendTeperatureTS(temp);
    int count = myPeriodic;
    while(count--)
    delay(1000);
}

void connectWifi()
{
    Serial.print("Connecting to "+*MY_SSID);
    WiFi.begin(MY_SSID, MY_PWD);
    while (WiFi.status() != WL_CONNECTED) {
        delay(1000);
        Serial.print(".");
    }

    Serial.println("");
    Serial.println("Connected");
    Serial.println("");
}//end connect

void sendTeperatureTS(float temp)
{
    WiFiClient client;

    if (client.connect(server, 80)) { // use ip 184.106.153.149 or api.thingspeak.com
        Serial.println("WiFi Client connected ");

        String postStr = apiKey;
        postStr += "&field1=";
        postStr += String(temp);
        postStr += "\r\n\r\n";

        client.print("POST /update HTTP/1.1\n");
        client.print("Host: api.thingspeak.com\n");
        client.print("Connection: close\n");
        client.print("X-THINGSPEAKAPIKEY: " + apiKey + "\n");
        client.print("Content-Type: application/x-www-form-urlencoded\n");
        client.print("Content-Length: ");
        client.print(postStr.length());
        client.print("\n\n");
        client.print(postStr);
        delay(1000);

    }//end if
    sent++;
    client.stop();
}//end send


texts:
So I tried to save a little money and bought (5) HC-05 bluetooth modules off of our good buddy eBay.

When the modules arrived, as I was testing and setting up for my project (2 nano's connected via an HC-05 each to a Galaxy S4), I noticed all 5 modules shipped with the same MAC address.

I have been looking everywhere I can think of to modify the MAC address of the modules, but have had no luck.  Well, that isn't 100% accurate.  I found bdaddr on linux, but I do not have a linux machine.  Just Windows for me right now.

So, my issue is trying to find a way to set the HC-05 modules with different MAC addresses so I can have (2) connect at the same time to my S4.  I have been able to change the name of the units via the AT commands, just not the MAC address.

Thank you in advance for your help.


texts: How to access serial terminal through USBASP?

texts:
I have an Arduino Pro Mini that I use with a USBASP to program. These are actually a clone Pro Mini and a clone USBASP I'm using.

With this configuration, is it possible for me to access the serial port on the Arduino, through the USBASP, using the IDE serial terminal? If so, this would alleviate another connection to the computer for debugging. How to do this?


texts:
I've used the piezo on other projects with no problem, but for some reason this project isn't working out so hot.

Here's a photo of my current set up.

Here's the basic code that I presumed would make a sound, but no such luck.

void setup() {}

void loop() {
  tone(12,260);
  delay(10);
}

Not sure where to begin debugging this...


texts: How do I correctly use enum within a class?

texts:
I am trying to set the status of an object from a private enum and I'm not sure how to get the private member to the public version in the constructor, and I'm pretty sure I should not be using byte in the constructor when it's an enum.

Also, I'm not sure if I should even have the values of the enum inside the header at all. Here is my code:

.h

class CandleRack
{
  public:

    CandleRack(byte candleRackStatus);
    ~CandleRack();
    void begin();
    void pushButton();
    void selectRandomCandle();
    void turnOnCandle(byte candlePosition);
    void burnCandlesForMs();
    void fadeOutCandle(byte candlePosition);

  private:
    Bounce *_debouncePushButton;
    byte _pushButtonPin;
    enum _candleRackStatus
    {
      inactive = 0,
      candlesOn = 1,
      rewardAnimation = 2,
      tweetArrived = 3,
      partyMode = 4,
    };
    byte _candlePosition;
    byte _candleStatus[NUM_LEDS];
    elapsedMillis _candleTimeElapsed[NUM_LEDS];
    unsigned int _candleOnForMs;
};

.cpp

CandleRack::CandleRack(byte candleRackStatus)
{
  _candleRackStatus = candleRackStatus;
  _debouncePushButton = NULL;
}

in the sketch

CandleRack MyCandleRack(0);

error:

error: expected unqualified-id before '=' token
_candleRackStatus = candleRackStatus;

Thanks!


texts:
I got this question from my teacher the other day and I can't figure it out:

  If you have two sensors from two different outputs but want them to go into one input, what do you need, and how can you read the input?

In short, the project includes an Arduino Uno with two ultrasonic sensors.


texts: Websockets with the ESP8266 using arduino uno board

texts:
I'm trying to make an iot device that connects to my wifi, establishes a socket connection with my golang backend and then starts to send sensor data from the ardunio.

I've got an ardunio uno board and this ESP8266:

I found this websockets library but I don't know if I can import the .h files if I have "arduino uno" selected in the IDE

My question:
Is it possible to establish a WebSocket connection with my go backend using the esp model that I have? If so, how can I import the required libraries in the arduno IDE? I would be happy if you could give me some directions.


texts:
I am trying to store a large number of values into a couple of arrays using PROGMEM, but I am finding that a few of the values are read back corrupted. I am storing just 1s and 0s, but when I read these values back, I will sometimes get values greater than 1. I am using a MEGA 2560 to do this.

// Each array contains 32000 values
const byte VALUES_1[] PROGMEM = { 1, 0, 1, .... 0 };
const byte VALUES_2[] PROGMEM = { 1, 1, 0, .... 0 };
const byte VALUES_3[] PROGMEM = { 1, 0, 1, .... 1 };
const byte VALUES_4[] PROGMEM = { 1, 0, 1, .... 1 };
const byte VALUES_5[] PROGMEM = { 1, 0, 1, .... 1 };

const long ARR_LEN = 32000;
long index = 0;

void setup() {
  Serial.begin(57600);
  while (!Serial) {}
}

byte readNextValue() {
  if (index >= 160000L) {
    return -1;
  }

  Serial.print(index);
  Serial.print(" ");

  long arr = index / ARR_LEN;
  long i = index % ARR_LEN;
  index++;

  byte j = -1;
  switch(arr) {
    case 0:
      j = pgm_read_byte_far(VALUES_1 + i);
      Serial.println(j);
      return j;
    case 1:
      j = pgm_read_byte_far(VALUES_2 + i);
      Serial.println(j);
      return j;
    case 2:
      j = pgm_read_byte_far(VALUES_3 + i);
      Serial.println(j);
      return j;
    case 3:
      j = pgm_read_byte_far(VALUES_4 + i);
      Serial.println(j);
      return j;
    case 4:
      j = pgm_read_byte_far(VALUES_5 + i);
      Serial.println(j);
      return j;
  }

  Serial.println("Unable to return next value");
  return -1;
}

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

What I have noticed is that when I use pgm_read_byte_far for case 0 I will get garbage values for right away, but using pgm_read_byte_near will cause these garbage values to occur sometime later. Any insight to this problem is appreciated.


texts: I would like to write code in Arduino language, compile it in the Arduino IDE, grab the resulting binary code, and flash it to the Due via the TX/RX UART pins, bypassing both the USB Programming Port and Atmel16U2 chip. Before the UART flash, I am manually toggling the Erase and Reset pins on the Due to initiate a hard reset of the SAM3X chip, and SAM-BA now waits for the code. I would like to know: can I directly grab the binary code compiled by the Arduino IDE and give it to SAM3X via UART or is there extra code baked into that binary by the Arduino compiler that would cause this method to fail?


texts: Can't upload to my Nano after updating to Arduino AVR Boards 1.6.21

texts:
I recently had the Arduino IDE notify me of available boards updates, so I updated. Since then when I try to upload to my Nanos it fails:

avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0x01

avrdude done.  Thank you.

Problem uploading to board.  See http://www.arduino.cc/en/Guide/Troubleshooting#upload for suggestions.

I installed Arduino IDE 1.0.6 and found that I can upload to all my Nanos with that IDE version.

How can I upload to my Nanos using Arduino AVR Boards 1.6.21?


texts: USART RX Interrupt on an ARDUINO PRO MINI containing factory bootloader

texts:
Is it possible to use RXC Interrupt vector with the factory programmed bootloader still existing in the arduino pro mini?

I've written a simple echo program using RXC interrupt vector, the program prints "READY" on startup but as soon the chip receives the first character it goes into a repetitive reset loop i.e. I keep receiving READY READY READY.. so on.

I've checked the program multiple times and I think its the bootloader, I think the bootloader has shifted the interrupt table to the boot section before executing the application. Is that so?

Thanks in advance.


texts: Analog vs Digital Accelerometers - pro's and con's?

texts:
For my project i need to measure accelerations up to 16g. My options are either digital accelerometers such as the MPU6050 or MPU9250 or an analog accelerometer such as the ADXL326.

What are any major pro's and con's of each. number of wires would be almost equal. the digital accelerometer is less pins on the board but i could easily use analog to digital convertors to bypass that. sampling rate is lower at 550Hz for the analog vs 4000Hz for the MPU9250. However i believe 550Hz would be more than adequate. And the biggest difference for me. £2 for an MPU9250 and £12 for the ADXL326!

Does anyone have any general advice on the main differences when choosing between analog and digital? I am measuring suspension motion on a motorcycle and need 5 of these accelerometers.


texts:
There are some discrepancies between what is read by the analog channel for a thermistor, ohms values directly obtained on the thermistor using an ohmmeter, and another digital temperature sensor.

Figure 1: Left column (y axis) is degree Celcius; x axis is time (minutes). Orange is what was read by the analog channel (thermistor); in yellow the reading by a commercial digital sensor; and in green, manual readings of the thermistor using a ohm-meter.

A bit more context, we are building a simple system to read the temperature from a thermistor via an analog channel. Code algorithm is very similar to what is found here and the electronic layout inspired from here. When we ran into problems,  we just went back to the working basics as instructed by those two above-mentioned references.

Pad resistor is 7K Ohms @ +/-1%, measured resistance was 6690 ohms
Thermistor is 2252 Ohms @ 25 degree Celsius. Coefficients are as follow, coefficient were solved following a calibration in a thermal bath:

COEFF_A = 0.0014644
COEFF_B = 0.00023888
COEFF_C = 9.8996E-08

Specs from vendor are here (PDF) factory coefficient are about the same. I tried to calculate with either factory and in-house calibrated and there is a few thousandth of a degree of difference between the two - not enough yet to explain the current problem

While investigating I saw some sketch with the same resistance for pad resistor and thermistor, but have seen other differing thus assume this is not an issue.

To troubleshoot and isolate the origin of the discrepancies of the orange line VS other reading, we used

other thermistors (every single one behave similarly as the orange line in the figure 1)
other digital temperature sensors (every single one behave similarly as the yellow line in the figure 1)
we try to put 2 analog thermistors and 2 digital temperature sensors on the same arduino - analog were consistant between each other (discrepancies) and the digital one were behaving as expected (correctly)
we switched the pad resistor, no effect
other arduinos (did not changed anything, every single one was repeatedly demonstrating the same behaviour )
used the system in a temperature controlled room and the discrepancy was still present for the analog channel and absent for the digital sensor.

To be clear, green and yellow are what we think is the 'real' temperature; and the orange is the discrepancy. About 1 - 2 degree differences

We used the raw analog value read by the arduino as an input to manually feed and solve the Steinhart–Hart equation (like using IPYTHON and by hand) and output is the same as the orange line. Did the same with the thermistor obtained by the ohm-meter (Green dots on figure).

What should be investigated next to solve the discrepancy between what is read by the analogue channel connected to a thermistor and what the same thermistor provide to the ohm-meter?

Sketch follows

#define THERMISTORPIN_0 0               // analog pin 0 on the board
#define SERIESRESISTOR_0 6990             // balance/pad resistor value (ohm)
#define THERMISTORNOMINAL 2252          // resistance at 25 degrees C
#define ZEROABS -273.15                 // zero Kelvin (Celsius)

#define COEFF_A 1.4644E-03          // Coefficient A for Steinhart-Hart eq.
#define COEFF_B 2.3888E-04          // Coefficient B for Steinhart-Hart eq.
#define COEFF_C 9.8996E-08          // Coefficient C for Steinhart-Hart eq.

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

void loop()
{
    float temp1;
    temp1 = Thermistor(analogRead(THERMISTORPIN_0),SERIESRESISTOR_0);
    Serial.println(temp1);
}

float Thermistor(int RawADC, long padResistance) {
  long Resistance;
  float Temp;
  Resistance = padResistance / ((1023.0 / RawADC) - 1);
  Temp = log(Resistance);
  Temp = 1 / (COEFF_A + (COEFF_B * Temp) + (COEFF_C * pow(Temp,3)));
  Temp += ZEROABS;

  return Temp;
}


texts: Replacing large lookup table with switch statement

texts:
My arduino needs to take a 14-bit number and convert it to a 10-bit number. Can't use a formula for it since the data is quite random. So I created a lookup table with 2^14 elements, each containing a 10-bit value. But it's too big to fit on the arduino. So I thought of using a switch statement instead. Would this result in a significant speed decrease?

Say, for example, that the input value is 16383. How much longer would it take for the arduino to iterate through the 16384 cases compared to accessing index #16383 of an array?

EDIT: This code compiles fine and reports a program memory usage of 1000 bytes.

int xval;
int yval;

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

void loop() {
  xval = random(0,16383);
  switch (xval) {
  case 0:
  yval = 0;
  break;
  case 1:
  yval = 4;
  break;
  case 2:
  yval = 4;
  break;
  case 3:
  yval = -60;
  ...
  case 16383:
  yval = 1023;
  break;
}
}

However, I haven't tried if it really works so maybe the compiler is optimizing away too much.

EDIT 2: Added the line Serial.println(yval); so that I'm actually doing something with yval as Majenko commented. And now it doesn't compile :'( :'( :'(

So, I'll tackle my problem in some other way.


texts: Can a function be called automatically when an input changes?

texts:
Currently, my sketch is checking an input pin every time round the main loop. If it detects a change, it calls a custom function to respond to it. Here's the code (trimmed down to the essentials):

int pinValue = LOW;

void pinChanged()
{
    //...
}

void setup()
{
    pinMode(2, INPUT);
}

void loop()
{
    // Read current input
    int newValue = digitalRead(2);

    // Has the input changed?
    if (newValue != pinValue) {
        pinValue = newValue;
        pinChanged();
    }
}

Unfortunately, this doesn't always work properly for very short changes on the input (e.g. brief pulses), especially if loop() is running a bit slowly.

Is there a way to make the Arduino detect the input change and call my function automatically?


texts:
This is my first post. Please excuse me if this is a repost, but I couldn't find a similar question via search.

I have some experience with Arduino and I'm looking to utilize AVR's sleep mode in a project. I followed along with this tutorial here. However, when I modify the code as follows, the uC seems to wait 4.09 seconds before waking up the first time. After that, it wakes up repeatedly (about every 6 milliseconds).

In my mind, the Arduino should enter sleep mode and not wake until the timer interrupt wakes it every 4.09 seconds (and then repeats and sleeps again). When I add a delayMicroseconds() after each wake up, it seems to function correctly. I want to accomplish sleep until interrupt wakes, perform interrupted action, then go back to sleep. What's going on? Am I missing something obvious? Is the Serial.println() causing an interrupt that wakes the uC right as it enters sleep?

Thanks for the help!

#include <avr/sleep.h>
#include <avr/power.h>

ISR(TIMER1_OVF_vect)
{
 //do nothing
}

void enterSleep(void)
{
  set_sleep_mode(SLEEP_MODE_IDLE);

  sleep_enable();

  /* Disable all of the unused peripherals. This will reduce power
   * consumption further and, more importantly, some of these
   * peripherals may generate interrupts that will wake our Arduino from
   * sleep!
   */
  power_adc_disable();
  power_spi_disable();
  power_timer0_disable();
  power_timer2_disable();
  power_twi_disable();

  /* Now enter sleep mode. */
  sleep_mode();

  /* The program will continue from here after the timer timeout*/
  sleep_disable(); /* First thing to do is disable sleep. */

  /* Re-enable the peripherals. */
  power_all_enable();
}

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

  /*** Configure the timer.***/

  /* Normal timer operation.*/
  TCCR1A = 0x00;

  /* Clear the timer counter register.
   * You can pre-load this register with a value in order to
   * reduce the timeout period, say if you wanted to wake up
   * ever 4.0 seconds exactly.
   */
  TCNT1=0x0000;

  /* Configure the prescaler for 1:1024, giving us a
   * timeout of 4.09 seconds.
   */
  TCCR1B = 0x05;

  /* Enable the timer overlow interrupt. */
  TIMSK1=0x01;
  while(!Serial);
}

void loop()
{
    enterSleep();
    Serial.println("Waking");
    //delayMicroseconds(10000);
}


texts: Not clear code procedure in Arduino wire library

texts:
The application code of sparkFun, has the following line which is difficult to understand.

It's requested 6, because it's requesting 6 bytes for HMC5883L module.

Wire.requestFrom(address, 6);
if(6<=Wire.available())

Where:

int TwoWire::available(void)
{
  return rxBufferLength - rxBufferIndex;
}

So, the available function should return return rxBufferLength - rxBufferIndex; where rxBufferIndex is modified in read function:

int TwoWire::read(void)
{
  int value = -1;

  // get each successive byte on each call
  if(rxBufferIndex < rxBufferLength){
    value = rxBuffer[rxBufferIndex];
    ++rxBufferIndex;
  }

  return value;
}

But, my current question is why decrementing return rxBufferLength - rxBufferIndex; where rxBufferIndex is initialized to 0 all the time, and there's no chance the returned value would be less than 6, because that would terminate the if statement?


texts: Networking Multiple Arduinos -- Is It "Rocket Science?"

texts:
Have a set of Arduinos that need to swap data--for a model rocket launch controller!
How to send 24 bits of info (launch commands) from a "master" Arduino, 12 bits each to two "slave" Arduinos that are 15' to 150' away from the "master.
Each "slave" needs to send 12 bits of info (continuity statii) to the "master."
"Master" <--- 15' to 115' ---> "Slave 1" <--- 10' to 35' --> "Slave 2"
Seems too long for I2C?


texts: Trying to get a ILI9341 TFT to work with UTFT library

texts:
I'm currently trying to fill out the constructor but I'm not sure what's what...
The constructor of the UTFT library goes as follows:

UTFT(Model, SDA, SCL, CS, RST[, RS]);

Where the last bit is optional.

SDA meaning Serial Data, SCL serial clock, CS chip select, RST reset and RS register select.

This is the screen I'm trying to connect. As far as I understand:

SDI (MOSI) goes to SDA

SCK goes to SCL

CS  goes to CS

RST goes to Reset?

RS goes to D/C?

But it doesn't work. What am I missing...

Here's my full code:

#include <UTFT.h>

//Digital Pins:
//53 = MOSI
//52 = SCK,
//10 = CS
//6 = RS
//7 = D/C
UTFT myGLCD(ILI9341_S5P,53,52,10,6,7);

void setup() {
    myGLCD.InitLCD(PORTRAIT);
    myGLCD.clrScr();

}

void loop() {
    myGLCD.fillScr(0,0,255);

}

I did get the screen to work with the Adafruit_GFX library. I used 1k resistors between all of the data lines, including reset. When using the screen with the GFX library I connected reset to 3,3v.


texts: Cutting off OneWire/SDA line with transistors

texts:
I am developing a pcb for a design I am working on and I need to share a pin to be used by a ds18b20 (onewire) and some possible I2C sensors. There would be just one of each at a time.

I was thinking about using a couple of transistors. One would cut or enable ds18b20 data line and the other one, the same for SDA line. So I would enable the first one and disable the second one or viceversa.

Do you think this is possible? I don't have transistors right now to test it. I have to order some of them. I was thinking about a bd228. Would this add some errors/delays/whatever in signal information? A kind of distorsion I mean. Or should it work?

EDIT: I will try to explain a bit my project.

My idea is to have a box with 5 sockets. Each one of them will be a different data input. They should be able to use a wide variety of sensors, ds18b20, dht22, open/close door (1 or 0 signal)... Also I would want to include some I2C sensors.

I was thinking about BME280 for example.

My idea is that the user could set which sensor is connected each time so the arduino can switch transistor behaviour to allow the connectivity to the digital pin or the I2C SDA (or SCL) pin.

I was thinking about using an I2C multiplexer to allow multiple BME280 to be at the same time so the first line would go to the socket1, second line socket 2...


texts:
I have recently started working on esp8266 wifi module and arduino uno.
I am a little confused.

I have created a small Web page with esp8266 AT commands.
Now I want use it for receiving data such as changes on the Arduino inputs.

I have seen many similar implementations using jQuery for that purpose,
but I don't know where to place that jQuery file.

Furthermore, is it possible to use NODEMCU firmware and still toggle arduino pins and transmit data to esp8266?

I want to use Arduino for:

reading voltage levels
publish the values read to the Web page
toggle a relay when a button on the Web page is pressed.

Please kindly help me out or point me in the right direction to search


texts: Unable to use RGB matrix and the serial monitor at once

texts:
Recently I bought the following matrix:
https://learn.adafruit.com/32x16-32x32-rgb-led-matrix/overview

I own an Arduino Uno for those who are interested.

I got the 32x32 variant and I am very happy with it. I managed to connect all the wires correctly and get the examples of the library working.

The problem I am facing right now is I can't get it to work properly for a personal project of mine. Somehow I am unable to use the serial functions and the matrix library functions in one project.

Currently my project looks like this:

My Arduino is connected like this:

And the code I wrote is:

#include <gamma.h>
#include <RGBmatrixPanel.h>
#include <Adafruit_GFX.h>
#include <gfxfont.h>

#define CLK 8
#define OE  9
#define LAT 10
#define A   A0
#define B   A1
#define C   A2
#define D   A3

RGBmatrixPanel matrix(A, B, C, D, CLK, LAT, OE, false);
String incomingCommand = "";

void setup() {
  Serial.begin(9600);
  matrix.begin();
  matrix.fillRect(0, 0, 32, 32, matrix.Color333(0, 0, 0));
}

void loop() {
  if (Serial.available() > 0) {
    int incomingByte = Serial.read();
    char receivedChar = (char) incomingByte;
    incomingCommand += receivedChar;
  }

  if (incomingCommand.indexOf('#') > - 1 && incomingCommand.indexOf('%') > - 1) {
    String rawCommand = incomingCommand.substring(incomingCommand.indexOf('#'), incomingCommand.indexOf('%') + 1);
    rawCommand = rawCommand.substring(1, rawCommand.length() - 1);
    Serial.print("Following command received: ");
    Serial.println(rawCommand);
    if (rawCommand == "turnledon") {
      matrix.drawPixel(0, 0, matrix.Color333(7, 7, 7));
    }
    incomingCommand = "";
    rawCommand = "";
  }
}

The idea is that a command gets sent from the serial monitor. Based on the command one led on the matrix will turn on. An example of a future command will look similar to this: "#drawPixel_X1_Y2%", hence the part that checks on "#" and "&".

The problem is that the functionality of the serial monitor isn't working with line 14 and 48 of the code. As soon as I remove those lines, the serial monitor works perfectly and I can receive and write to the serial monitor. I have no idea what is causing this.

I was wondering if someone ever faced a similar problem or knows what I am doing wrong right now.

Thank you in advance!


texts:
I am trying to control a strip of WS2801 LEDs through an arduino uno running firmata from Python on my laptop.

I've written some basic code based on adafruit's library here (from line 187):

from pymata_aio.pymata3 import PyMata3
from pymata_aio.constants import Constants
import time

leds = [(255, 255, 0), (255, 255, 0), (0, 255, 255)]

uno = PyMata3()

uno.set_pin_mode(2, Constants.OUTPUT)  # signal
uno.set_pin_mode(3, Constants.OUTPUT)  # clock

def show(leds):
    for pixel in leds:
        for channel in pixel:
            i = 0b1
            for x in range(0,8):
                if i & channel:
                    uno.digital_write(2, 1)
                else:
                    uno.digital_write(2, 0)
                uno.digital_write(3, 1)
                uno.digital_write(3, 0)

                i = i << 1

    uno.digital_write(3, 0)
    time.sleep(0.001)

When I run the code it seems to run ok, but only the first LED will light up. I think (too quick to be certain) that it flashes through all the colours - ie displaying each colour rather than passing them through.

I'm wondering if there is something wrong with the timing for the clock pin making it latch, but I'm grasping here.


texts: I can't run shell commands on Linux through AVR sketch (Arduino Yun)

texts:
I'm a little confused with some Process.h methods.
I'm trying to run the command "nc 192.168.1.15 9911" to the Linux processor through a sketch.
The appropriate netcat listener is waiting on another computer. Arduino Yun is on the same network with thie computer via WiFi.
When I execute this command through SSH connection on Arduino Yun it works fine, but I can't figure out how it's done through a sketch.
This is my code:
#include <Process.h>

Process p;

void setup() {
   Bridge.begin();
   Serial.begin(9600);
   delay(2000);
   p.begin("nc");
   p.addParameter("192.168.1.15 9911");
   p.run();
   //while (!p.running()) {};

 }

 void loop() {
    if (p.available() > 0) {
    Serial.println("test");
 }
}

This code doesn't seem to work, p.available() nerver executes even if I send data packets.
I also tried p.runShellCommand("nc 192.168.1.15 9911"); with no luck.
It seems that the commands never reach the Linux command line.
Any insights?


texts: Can't use two SPI devices at the same time

texts:
I can use the MFRC522 using the following code:

#include <SPI.h>
#include <MFRC522.h>

MFRC522 mfrc522(10, 9);

void setup() {
    SPI.begin();
    mfrc522.PCD_Init();
}

void loop() {
    if (  mfrc522.PICC_IsNewCardPresent() && mfrc522.PICC_ReadCardSerial() ) {
         // Do stuff
    }
}

And it works great. I can also use the dot-matrix (8x8) using the following code:

#include "LedControl.h"

LedControl lc = LedControl(12,11,8,1);

void setup() {
    lc.shutdown(0,false);
    lc.setIntensity(0,3);
    lc.clearDisplay(0);

    lc.setLed(0,2,5,true);
    lc.setLed(0,5,5,true);

    lc.setLed(0,2,2,true);
    lc.setLed(0,3,1,true);
    lc.setLed(0,4,1,true);
    lc.setLed(0,5,2,true);
}

void loop() {
}

And it works just fine as well. However, when I try to use both of them using the following code:

#include <SPI.h>
#include <MFRC522.h>
#include "LedControl.h"

LedControl lc = LedControl(12,11,8,1);
MFRC522 mfrc522(10, 9);

void setup() {
    SPI.begin();
    mfrc522.PCD_Init();

    lc.shutdown(0,false);
    lc.setIntensity(0,3);
    lc.clearDisplay(0);

    lc.setLed(0,2,5,true);
    lc.setLed(0,5,5,true);

    lc.setLed(0,2,2,true);
    lc.setLed(0,3,1,true);
    lc.setLed(0,4,1,true);
    lc.setLed(0,5,2,true);
}

void loop() {
    if (  mfrc522.PICC_IsNewCardPresent() && mfrc522.PICC_ReadCardSerial() ) {
         // Do stuff
    }
}

In that case only one of them works (the MFRC522). I know that since they are connected in SPI mode they need to have different SS pins, so I used pin 10 for MFRC522 and pin 8 for dot-matrix. So, what's wrong? Why dot-matrix doesn't work at the same code with MFRC522??


texts:
I am using a grove GPS http://www.seeedstudio.com/wiki/Grove_-_GPS

I attached the GPS to Serial1 of Arduino Mega 2560.

The baudrate of the GPS is set to 9600.

Library wise, I am using TinyGps to parse the GPS data.

The GPS receiver can only get a valid data if it can see a clear sky.

I read uBlox documentation and it states that I can use A-GPS.

So, my question is, how do I actually set the Grove GPS that is attached to my Mega, to use A-GPS?


texts: Flickering LCD when using > 5v power supply on a Pro Mini

texts: I have a Pro Mini wired up to an LCD via an I2C board. At http://www.arduino.cc/en/Main/ArduinoBoardProMini it says the pro mini can accept up to 12v on the RAW pin as it has a voltage regulator on board. When I plug a 12v power supply into the raw pin, the LCD works fine initially, then slowly degrades into flickering more and more. It also does this with a 9v power supply. At 5v it works perfectly. Any ideas what's going on?


texts:
I tried testing the system and I’m not sure if the problem is with the XBee’s, the transmitting code, or the receiving code. Before I post my code, I will explain what we are doing with the signals.

We have three analog signals that will be sent serially through one XBee using an Arduino and XBee shield.  We want to send these signals to the receiving xbee where the Arduino will output these signals to be connected to a third Arduino through wires to be used in a Simulink program.

We are using an Arduino mega for the transmitting side and an Arduino uno for the receiving side. I was told I need to do serial streaming but I’m not sure how that’s done. I understand the XBee and Arduinos both digitize signals but we are hoping to get a signal very similar to the analog signals we are transmitting. Any amount of help is greatly appreciated!!

This is how I have my XBees configured (series 1) both in AT mode:

  Transmitting XBee:
      Channel:10
      Pan id: 1234
      MY: 10
      DL: 11

  Receiving XBee:
      Channel:10
      Pan ID: 1234
      MY: 11
      DL: 10

Transmitting Arduino code:

void setup() {
  Serial.begin(9600);
}
void loop() {
  // read the input on analog pins
  int sensorValue1 = analogRead(A0);
  int sensorValue2 = analogRead(A1);
  int sensorValue3 = analogRead(A2);
  // print out the value you read:
  Serial.println(sensorValue1);
  Serial.println(sensorValue2);
  Serial.println(sensorValue3);
  delay(1);
}

Receiving Arduino code:

int received1=8;
int received2=9;
int received3=10;
void setup(){
  pinMode(received1, OUTPUT);
  pinMode(received2, OUTPUT);
  pinMode(received3, OUTPUT);
  Serial.begin(9600);
}
void loop(){
  if(Serial.available() )
  {
    byte output1 = Serial.read();
    byte output2 = Serial.read();
    byte output3 = Serial.read();
    digitalWrite(received1, HIGH);
    digitalWrite(received2, HIGH);
    digitalWrite(received3, HIGH);
  }
}


texts:
My target is to make an Arduino system that is able to change modes with different delays by pushing a button. For example, if I pressed the button, it will go into mode 1 with loop 1 that has a 30s delay. If I pressed it one more time, it will go to mode 2 with with loop 2 that has a 1 min delay, etc. The important thing is that mode 1 should be breaked when the push button pressed.

The code below solved part of the problem. However, LEDs are only constant ON, they are not blinking for a certain time then it turned either on-off within the mode when the push button pressed.

int b =3;int rl= 5;int gl=6;
int yl=7; int s=0; int o=0;
 int bp =0;

void setup() {
  // put your setup code here, to run once:
pinMode(b,INPUT);
pinMode(rl,OUTPUT);
pinMode(gl,OUTPUT);
pinMode(yl,OUTPUT);

 digitalWrite(rl,LOW);
digitalWrite(gl,LOW);
digitalWrite(yl,LOW);
}

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

bp=digitalRead(b);
if (bp==1){
  delay(50);
  bp=digitalRead(b);
  if (bp==0){
    s=o+1;}}
    else{
      delay(100);}
      switch(s){
        case 1:
        digitalWrite(rl,HIGH);
digitalWrite(gl,LOW);
digitalWrite(yl,LOW);
o=s;
break;

case 2 :
digitalWrite(rl,LOW);
digitalWrite(gl,HIGH);
digitalWrite(yl,LOW);
o=s;
break;

case 3:

digitalWrite(rl,LOW);
digitalWrite(gl,LOW);
digitalWrite(yl,HIGH);
o=s;
break;
default:

digitalWrite(rl,LOW);
digitalWrite(gl,LOW);
digitalWrite(yl,LOW);
o=0;
break;}}

S1 is responsible to activate D12 to be constant ON (when it’s pressed once) which lead UNO2 to be powered then blink the right LED ON (1min) OFF(4Hr), (pressing it twice should turn D12 OFF (optional)). The same thing with S2, when it’s pressed once it should first disable D12 and activate D11 instead, powering UNO3, blinking the left LED ON(30S), OFF (4Hr).

In addition, blinking on() off() repeatedly is needed (unless action break/occur, ex: pressing S1 or S2).

About S1 and S2. The LED on D12 will flash ON for 1 minute then turn off for 4 hours. After the 4 hours, the LED on D12 will flash ON again for 1 min then turn off for 4 hours again & again...as an infinite loop. With S2 The LED on D11 will flash ON for 30 seconds then turn off for 4 hours. After the 4 hours, the LED On D11 will flash ON again for 30 s then turn off for 4 hours again and again as an infinite loop.


texts: How to use multiple SPI slaves in MKR1000 if it doesn't have Slave Select (SS/CS) pin?

texts:
I'm using a Genuino MKR1000 and I want to use the SPI interface, which I've seen that there is no Slave Select (SS)/Chip Select(CS) pin usage.

How can I use the SPI interface with multiple slaves then?


texts:
Hi we were asked to program something which when i enter something in the serial monitor it prints Hello world but the catch is it only prints hello world under the conditions that your input in the serial monitor is a 3 bit input and after that i need to have a code which then stops it from printing over and over again.
my only problem is that i don't really know how to count the number of bits of an input and also to stop it from printing continuously.

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

}

void loop() {
  String readSerial;
    String input;
    while(Serial.available() > 0){// put your main code here, to run repeatedly:
    delay(2);
  input.concat(String((char)Serial.read()));
  return input;
  }
  Serial.println("HELLO WORLD");
}


texts: Black screen when using higher SPI-speed for RA8857 LCD-controller

texts:
I'm using an Arduino Due that talks via SPI to an LCD (800x480) with the RA8875 controller chip.
The most recent datasheet I could find is: RA8875 datasheet.
Everything works as expected when using the Adafruit library. But, for my project, I want to maximize the communication speed between the LCD and the Arduino DUE.
Page 60 of the datasheet tells me that the maximum SPI speed to perform a SPIread is

system clock / 6.

Page 39 gives the formula for the system clock:

SYS_CLK = FIN * ( PLLDIVN [4:0] +1 ) / (( PLLDIVM+1 ) * ( 2^PLLDIVK [2:0] ))

There are some constraints:

From page 39:
FPLL = FIN * ( PLLDIVN [4:0] +1 ) must be equal to or greater
than 110 MHz

From page 91:
For an LCD of dim 800x480 2 layers 8bit color depth 60Hz framerate the pixel clock should be between  30 and 33MHz. (Registers are set to have 2 layers and 8 bit color depth).

A crystal of 20Mhz is soldered on the LCD ( FIN = 20 Mhz)
I have set the registers as follows:

Register
Value

PLLC1[88h]
24

PLLC1[89h]
1

PCSR[04h]
3

So, I expect:

SYS_CLK  = 20 Mhz * ( 24 +1 ) / (( 0+1 ) * ( 2^1 )) = 250 Mhz
Pixel clock = SYS_CLK / ( 2^3 ) = 31.25 Mhz
Max. spi speed = 250 Mhz / 6 = 41.66 Mhz.

I think to obey every given constraint.
But when I use an spi-speed of 30 Mhz, which is below 41.66 Mhz, I get a black screen.
I've put the Arduino sketch and the modified Adafruit library (Sven_RA8875) on google drive:
Arduino sketch + modified library.
The same data but on a pastebin:
Image: Working LCD at 20 Mhz
Example code RA8875
Modified library .cpp
Modified library .h
Edit by PPK:
I add the pictures from paste pics to this post after I scaled and croped them.


texts: How can I send/write two doubles via Bluetooth (nRF8001 Bluefruit LE) in Arduino?

texts:
I recently purchased an nRF8001 Bluefruit LE and I am now trying to read/send data with an app. But I am not sure how I can write/send a double value. I want to send two double values at once and to successfully send this, do I have to convert these doubles to a byte array? If so I would very much appreciate how that would look!

This is documentation on how my module works:
https://learn.adafruit.com/getting-started-with-the-nrf8001-bluefruit-le-breakout/nrf-uart-in-detail

Under the headline Writing data they give examples on how to send data but as far as I can see (I am a bit new to Arduino code) in their example they only send an int and a string.

I know how to read and set up the module, so it is only the writing/sending doubles that I am struggling with.

These are the two doubles that I wish to send and I control it with:

double valueOne;
double valueTwo;

The Bluetooth control:

Adafruit_BLE_UART BTLEserial = Adafruit_BLE_UART(ADAFRUITBLE_REQ, ADAFRUITBLE_RDY, ADAFRUITBLE_RST);

So if I for example do this:

BTLEserial.write(valueOne, valueTwo);

I get this message: no matching function for call to 'Adafruit_BLE_UART::write(double&, double&)'

So do I need to convert these two double values to a byte array and if so how would that look?

Appreciate every help, tips, code! :)


texts:
My code:

// Pin 13 has a LED connected on most Arduino boards.
// give it a name:
int led = 13;
const int buttonPin = 2;

// the setup routine runs once when you press reset:
void setup() {
  // initialize the digital pin as an output.
  pinMode(led, OUTPUT);
  pinMode(buttonPin, INPUT_PULLUP);
}

// the loop routine runs over and over again forever:
void loop()
{
  bool buttonState = digitalRead(buttonPin);
  while (buttonState == LOW)
  {
   digitalWrite(led, HIGH);   // turn the LED on (HIGH is the voltage level)
   delay(1000);               // wait for a second
   digitalWrite(led, LOW);    // turn the LED off by making the voltage LOW
   delay(1000);               // wait for a second
   }
 if (buttonState == HIGH){
   digitalWrite(led, LOW);}
  }

The last line of code:

if (buttonState == HIGH){
   digitalWrite(led, LOW);}

Is what I tried using to turn the led off from its continuous blinking state. So the point of this project is to make the led's blink with a button, then turn them off with the same button. This has been bugging me for hours and I've done all the work but can't seem to get this last part done. What is being done wrong here?

EDITED for clarification:

The intention is that with each push of the button the LED is toggled between a blinking and a no-blinking state. The state of the LED is not driven by the level (pushed/unpushed) of the button itself, but by the pushing action itself.


texts:
I'm doing a project where in I'm using Arduino Due to measure the time difference of arrival of signals to four piezoelectric sensors. The piezo sensors where glued on a board and we want to localize the source of taps on the boards based from the TDOA of the vibration to the piezos.

Originally, we are using interrupts to raise flags once we have detected the signals (basically, we've set a threshold on the piezo voltage to say that we've 'detected' a signal) but that seems susceptible to noises especially when the environment has loud noises (music, voices on microphones, etc.).

So what we think as a solution is to perform signal processing. However, to do this, we need to measure the voltage of the incoming signal using the ADC.

So far, my target is to make the performance of this approach comparable to that of the one where we are using interrupts. As of now, the new approach is super sensitive to the difference on the taps giving it a high POE.

As I understand it, the main difference between the two approach is that the interrupt approach has a microsecond difference between counts making the difference of the taps to about 10 to 30 microsecond. However, the Analog approach has a 20 microsecond difference between each sample for each channel, making the count difference 20 second also. Even a count difference would make it 20 us.

Is there anyway to make this time faster? I know the ADC needs time to convert and push the data to the appropriate registers but I'm just trying to find ways to make this faster. I've read on the datasheet of the Due MCU that it has 14 ADC channels plus a temp sensor at the 15th. Maybe a way of doing this could be to reduce the number of channels? I don't know how.

Are there any way to make the ADC conversion of the Arduino Due faster?


texts:
I've a code which records sound to SD, then starts an FTP connection for a limited time. I want to make an automatic system which records then sends the sound file continuously. Now I'm recording sound for 3s, then opening a FTP connection for 3s. In that 3s interval, my python code (PC) is trying to download the data in ESP (it also runs continuously. However, sometimes if ftp time is not enough, my connection is interrupting and ESP is resetting itself. So, I dont want to fetch this file via my computer, ESP32 should send this file after the recording, then it should start recording after the successful connection. I couldn't configured the code in the Arduino Playground
I pasted my code below, waiting for suggestions for valid examples.
You can find the libraries here

#include <WiFi.h>
#include <WiFiClient.h>
#include "ESP32FtpServer.h"
#include <FS.h>
#include <SD.h>
#include "Wav.h"
#include "I2S.h"

const int record_time = 3;  // second
const char filename[] = "/sound.wav";
const int headerSize = 44;
const int waveDataSize = record_time * 88000;
const int numCommunicationData = 8000;
const int numPartWavData = numCommunicationData / 4;
byte header[headerSize];
char communicationData[numCommunicationData];
char partWavData[numPartWavData];
unsigned long starttime;
unsigned long endtime;
File file;

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

FtpServer ftpSrv;   //set #define FTP_DEBUG in ESP32FtpServer.h to see ftp verbose on serial

void setup(void) {
  Serial.begin(115200);
  WiFi.begin(ssid, password);
  Serial.println("");

  // Wait for connection
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("");
  Serial.print("Connected to ");
  Serial.println(ssid);
  Serial.print("IP address: ");
  Serial.println(WiFi.localIP());

  /////FTP Setup, ensure SD is started before ftp;  /////////
  if (SD.begin()) {
    Serial.println("SD opened");
    ftpSrv.begin("esp32", "esp32");   //username, password for ftp.  set ports in ESP32FtpServer.h  (default 21, 50009 for PASV)
  }
  CreateWavHeader(header, waveDataSize);

}

void loop(void) {

  SD.remove(filename);
  file = SD.open(filename, FILE_WRITE);
  if (!file) return;
  Serial.println("recording");
  file.write(header, headerSize);
  I2S_Init(I2S_MODE_RX, I2S_BITS_PER_SAMPLE_32BIT);
  for (int j = 0; j < waveDataSize / numPartWavData; ++j) {
    I2S_Read(communicationData, numCommunicationData);
    for (int i = 0; i < numCommunicationData / 8; ++i) {
      partWavData[2 * i] = communicationData[8 * i + 2];
      partWavData[2 * i + 1] = communicationData[8 * i + 3];
    }
    file.write((const byte*)partWavData, numPartWavData);
  }
  file.close();

  Serial.println("recording finished, ftp starting");

  starttime = millis();
  endtime = starttime;
  while ((endtime - starttime) <= 3000) // do this loop for up to 1000mS
  {
    ftpSrv.handleFTP();        //make sure in loop you call handleFTP()!!
    endtime = millis();
  }
  Serial.println("ftp finished");

}


texts:
Of course I know it is usefull to control the time of a delay, but any other use?

With a 16Mhz clock, each line of my program will take 1/16000000 second, right?

even a very very big line will only take 1/16000000 of a second ?

With a 8MHz clock, each line will take the double of the time, right?
So the whole "main loop"  will take the double time too, right?


texts: Error with AT+CIPSEND in ES8266 with arduino

texts:
I'm making simple web-server on esp8266 module connected to Arduino. And when +IPD,0,GET... I'm sending AT+CIPSEND=0,16. Then I write HELLOMYDEARFRIDE.
It says : send 16 bytes recived. OK. But in browser it says me that server haven't given any right response. What is problem in?

Code:

#include <SoftwareSerial.h>

SoftwareSerial softSerial(10, 11);
String ssid = "***";
String password = "***";
String _response = "";
#define DEBUG true
void setup()
{

  Serial.begin(115200);

  softSerial.begin(115200);
  connectWifi();
}

void connectWifi() {

  do {
    sendData("AT+RESTORE\r\n", 5000, DEBUG);
  } while (softSerial.find("OK"));
  do {
    sendData("AT\r\n", 2000, DEBUG);
  } while (softSerial.find("OK"));
  do {
    sendData("AT+CWMODE=1\r\n", 1000, DEBUG);
  } while (softSerial.find("OK"));
  do {
    sendData("AT+CWJAP=\"" + ssid + "\",\"" + password + "\"\r\n", 5000, DEBUG);
  } while (softSerial.find("OK"));

  do {
    sendData("AT+CIFSR\r\n", 1000, DEBUG);
  } while (softSerial.find("OK"));
  do {
    sendData("AT+CIPMUX=1\r\n", 1000, DEBUG);
  } while (softSerial.find("OK"));
  do {
    sendData("AT+CIPSERVER=1,5000\r\n", 1000, DEBUG);
  } while (softSerial.find("OK"));

}

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

  String response = "";

  softSerial.print(command);        long int time = millis();
  while ((time + timeout) > millis())
  {
    while (softSerial.available())
    {
      char c = softSerial.read();
      response += c;
    }
  }

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

  return response;
}
int connectionId,pin;
void loop()
{
    if (softSerial.available()) {
    Serial.write(softSerial.read());
  }
  if (Serial.available()) {
    softSerial.write(Serial.read());
  }

}


texts: Reading values with HC-05 and sending commands at the same time working inconsistently

texts:
Not good at coding at all, so I'm at a total loss here.

But I'm doing a project that involves controlling a larger DC voltage through a mosfet.
What I'm doing is I'm using a HC-05 to transmit data between a phone and the Arduino Uno. Seeing the value within a couple of seconds is necessary.

However, sending the mosfet gate a command to open or close up work very inconsistently. Sometimes never and sometimes it takes up to 30 seconds for it to register.

The code here is a short version of the project that I'm working on, but behaves similarly.

#define mosfet 11
int state = 0;
int gate = 0;
int maxgate = 255;
int mingate = 0;

void setup() {
  delay(2000);
  pinMode(mosfet, gate);
  analogWrite(mosfet, 0);   //starts closed
  Serial.begin(9600);
}

void loop() {
  while(Serial.available() > 0){
    state = Serial.read();

    for (int y=0; y <= 5; y+=5){
      delay(500);
      Serial.println("testphase 1");
      delay(500);
    }

    for (int y=5; y >= 0; y--){
      delay(250);
      Serial.println("testphase 2");
      delay(250);
    }

    if (state == '0') {
    gate = gate + 1;
    if(gate > maxgate) gate = maxgate;
    analogWrite(mosfet, gate);
    Serial.println(int(gate));Serial.print(", +1");
    state = 0;
    }

  if (state == '1') {
    gate = gate + 10;
    if(gate > maxgate) gate = maxgate;
    analogWrite(mosfet, gate);
    Serial.println(int(gate));Serial.print(", +10");
    state = 0;
    }
}
}

When sending 'State == 1', for example it will go through both for loops multiple times and the maybe sometimes do gate + 10. Sometimes the commands goes completely ignored.

I have no idea how I would interrupt a loop to execute the given command and then go back.


texts: Arduino Wifi Shield with monitor mode ( promiscuous mode )

texts: Is there a WiFi Shield or driver that supports monitor mode and receiving raw packets ?


texts:
I want to read the value of the register (8-bit). In particular I want to read the values of:

The Timer/Counter - TCNT0 ( Adress 0x26 (0x46) )
The output compare registers - OCR0A and OCR0B.

Is there a way to read them with the Arduino program?


texts: Getting gibberish serial port until button is pressed, plus the button is turning the leds off instead of on

texts:
I'm connecting a button to ESP8266.
Connection goes like this:
3v to one side of button, other side connected with GND and pin number 2 (no resistor).

Every time I connect the ESP both built in LED's stay on until I press the button, they turn off until I let go (even though code states otherwise).
Plus, When I monitor the serial, gibberish runs while ignoring my print commands, until I press the button then the serial stops outputting altogether.

When I run the serial without the button, everything works fine.
Am I connecting it wrong, or is the button damaged, or any other problem source?
Thanks in advance.

EDIT: I added the pinMode(BTN_PIN, INPUT_PULLUP) to take the resistor role; to the code, still not helping.


texts:
I was reading this thread:

Read RC receiver channels using Interrupt instead of PulseIn

and I have been trying to understand the code provided within.

While I was able to udnerstand most of it, I am still unable to find proper documentation on Arduino PCIFR and PINC?

Could someone please point me in the right direction?

Thanks in advance.


texts:
So, I have an ATTiny85 sending data, awesome.
I would like to have it send a message that consists of a few concatenated parts.

I have been reading about strings, buffers, chars, toCharArray and more for about 6 hours now and am completely puzzled by this.

Below, the variable deze will no transmit, but msg will.
So I tried to do something like char *deze = "hello" + "world"; but that also fails.

What would be the best way to construct a piece of data that will be send by my 433MHz transmitter. I need to combine INT, String and float before sending it as uint8_t (bytes?).

#include <RH_ASK.h>

#define R_PIN PB4
#define T_PIN PB1
#define L_PIN PB3

RH_ASK driver(2000, R_PIN, T_PIN);

void setup()
{
  if (!driver.init()){
    pinMode(L_PIN, OUTPUT);
    digitalWrite(L_PIN, HIGH);
    delay(500);
    digitalWrite(L_PIN, LOW);
    delay(500);
  }
}

void loop()
{
  char deze[5];
  char *msg = "gewonechar";

  String thijs = "thijs";
  thijs.toCharArray(deze, sizeof(deze)-1);

  driver.send((uint8_t *)deze, strlen(msg));
  driver.waitPacketSent();
  delay(200);
}

[edit]
This is the working code on the receiver side.

struct data {
  uint16_t id;
  uint16_t pin;
  uint16_t value1;
  uint16_t value2;
} myData;

void loop()
{
    uint8_t buf[RH_ASK_MAX_MESSAGE_LEN];
    uint8_t buflen = sizeof(buf);

    if (driver.recv(buf, &buflen)) {

      memcpy(&myData, buf, buflen);

      Serial.print("ID: ");
      Serial.println(myData.id);

      Serial.print("Pin: ");
      Serial.println(myData.pin);

      Serial.print("Value1: ");
      Serial.println(myData.value1);

      Serial.print("Value2: ");
      Serial.println(myData.value2);

      Serial.println("");
    }
    server.handleClient();
    yield;
}

And the transmitter

#include <RH_ASK.h>

#define BAUD 2000
#define RX 11
#define TX 12

RH_ASK driver(BAUD, RX, TX);

struct data {
  uint16_t id;
  uint16_t pin;
  uint16_t value1;
  uint16_t value2;
} myData;

void setup() {
    Serial.begin(9600);   // Debugging only
    if (!driver.init())
         Serial.println("init failed");
}

void loop()
{
    struct data myData;

    myData.id = 1001;
    myData.pin = 4;
    myData.value1 = analogRead(4);
    myData.value2 = analogRead(5);

    driver.send((uint8_t *)&myData, sizeof(myData));
    driver.waitPacketSent();
    delay(2000);
}

Library used: http://www.airspayce.com/mikem/arduino/RadioHead/


texts:
I have spent the whole day trying to deal with this problem connecting Arduinos together using UART (Serial). But the problem is that it always behaves weirdly. For now the problem is that if previous number (I am sending numbers over serial) stays in the serial port.

Let me describe the problem. I want to send the following sequence of numbers 16 4 100. Numbers are sent with a terminator char after each number, but on the receiver side I get the following result 16 46 100.

As you can see if the previous number is longer (length, has more digits) than the current one, like 16 and 4, 132 and 34, the difference (number of digits) remains in the next result: for 16 and 4 it will be 16 and 46, for 132 and 34 it will be 132 and 342.

I have tried different ways to solve this problem, but unfortunately I cannot find the solution.

Here are my functions used for communication:

void sendCommandToSerial(int command) {
  Serial3.print(command);
  Serial3.print(TERMINATOR_CHAR);
  Serial3.flush();
}

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

int readRawBytes(char *inputBuffer,const int bufferSize) {
  return Serial3.readBytesUntil(TERMINATOR_CHAR, inputBuffer, bufferSize);
}
int readIntFromSerial() {
  if(readRawBytes(inputBuffer,DEFAULT_BUFFER_SIZE) > 0) {
    return atoi(inputBuffer);
  }
  return -1;
}
int readFloatFromSerial() {
  if(readRawBytes(inputBuffer,DEFAULT_BUFFER_SIZE) > 0) {
    return atof(inputBuffer);
  }
  return -1;
}

I have tried both software and hardware serials, still the same.
Please help to find and solve the problem.


texts:
While running a program compiled in the Arduino IDE 1.8.5 and then using the .ELF file inside LabCenter Proteus 8.0, for an Arduino Nano ATMEL Mega 328P, for a code involving the use of the SoftwareSerial.h Library, hence involving several loops, without user interaction, I am getting the following error:

Invalid opcode 0x0024 at PC=0x0096

Now I am completely lost. According the AVR Instruction Set Manual such opcode should (not sure about this?) be RETI - Return From Interrupt at the Program Line (?) no.150 = 0x096. The full code has 779 lines plus several library calls, and the line 150 happens to fall just before the loop() function (?), which should never repeat, being just a declaration.

So, how should I debug this error? Evidently I am not asking to solve the problem for me but, how should I proceed for debugging it and find the real error?

I have been unable to find in Proteus a tool for "Debug Stop if Error"

I have been unable to isolate the error in a simple way to share. It should be related someway with interruptions used by the library SoftwareSerial.h, because at some modifications of the program, the code freezes at an interruption return. I am working on that, but advancing really slowly actually.

Related question No.1.


texts: How to connect Arduino Pro Mini with PC?

texts:
I'm about to buy Arduino Pro Mini (http://arduino.cc/en/Main/ArduinoBoardProMini).
As far as I can see it requires FTDI or similar circuit to program it.

Should FTDI be present for communication with PC after sketch is uploaded to chip or there is a way to connect Arduino Pro Mini DIRECTLY to USB cable and PC?

Is this also case with Arduino Pro Micro? (https://www.sparkfun.com/products/12640)

Thanks in advance
Petar


texts: MQTT (was WiFi) interference when using two nodeMCU devices

texts:
I have two nodeMCU boards, one from LoLin (192.168.1.52) and one from Amica (192.168.1.53). For each nodeMCU, I have mapped its MAC address to a fixed IP address using my Movistar WiFi router. I confirm from the serial monitor that each nodeMCU is being correctly assigned to the correct IP address

My sketch is a simple IoT/MQTT client.

My problem is that if I power up both nodeMCUs, the WiFi connection is broken on both.

The WiFi portion of my sketch is

void setup_wifi() {
  Serial.println(" Booting..");
  WiFi.mode(WIFI_STA);
  WiFi.begin(SSID, PASSWORD);
  while (WiFi.waitForConnectResult() != WL_CONNECTED) {
    Serial.println("Connection Failed! Rebooting...");
    myBlink(LED_PIN, 20, 100);
    delay(5000);
    ESP.restart();
  }
  WiFi.printDiag(Serial);
  Serial.println(WiFi.localIP());
}

The output is

Mode: STA PHY mode:
N Channel: 1
AP id: 0
Status: 5
Auto connect: 1
SSID (13): MOVISTAR_xxxx
Passphrase (20): 509A8EC4Exxxxxxxxx
BSSID set: 0

192.168.1.53 (or .52 on the other device)

I realise that the symptoms are consistent with clashing IP addresses, but to confirm, both the serial diagnostics and the DHCP report from my router confirm that the two devices are on different IP addresses.


texts: Can you pass params to an arduino sketch?

texts:
I was wondering if there is a way to pass parameters to an arduino sketch at the upload step.

Edit: The reason this would be helpful is because I have a bunch of esp8266 units that need to have details about their specific location but changing variables around per upload feels tedious.

If this is not possible the other solution that I am probably going to try is to have a sketch to just flash these details to eeprom and then read it from there whenever it is needed. Also storing them in eeprom feels a bit better than as literals in these sketches.


texts: My alterate flashing LED program is not working

texts:
I am trying to program my Arduino UNO ATMega 328p in assembler to implement a ﬂashing pattern with two LEDs. When one LED is oﬀ, the other must be on. I have made a program but it is showing errors and I don't know how to fix it. I have done it Atmel Studio 7. Please help if you can.

Here is my program:

main:

sbi 0x04, 5
sbi 0x04, 4

start:

sbi 0x05, 5
ldi r16,1000
rcall delay
cbi 0x05, 5

sbi 0x05, 4
ldi r16,1000
rcall delay
cbi 0x05, 4

rjmp start

delay:

dec r8
brne delay
dec r9
brne delay
dec r16
brne delay
ret


texts: Trying to connect a 1.3" IIC OLED display to an Arduino M0 board (not Uno)

texts:
I'm trying to connect an OLED display to the Arduino M0. I got the code example (ssd1306_128x64_i2c) from the Adafruit SSD1306 library I downloaded.

Video showing at 8:14 how it should look

However, when I upload the code to the board most of the display just lights up with no motion. It's only in the bottom that you can see the program is running, showing part of the different shapes.

After I uploaded it the first time I didn't change anything but now the compiler gives an error message saying that one display setting must be specified in SSD1306.h

I've tried setting the display size in the library header file which looks like this:

Displays
-----------------------------------------------------------------------
The driver is used in multiple displays (128x64, 128x32, etc.).
Select the appropriate display below to create an appropriately
sized framebuffer, etc.

    SSD1306_128_64  128x64 pixel display
    SSD1306_128_32  128x32 pixel display
    SSD1306_96_16

#define SSD1306_128_64
//#define SSD1306_128_32
//#define SSD1306_96_16

But the same error message appears in the compiler.

Does anybody know how I can fix this?

Thank you.


texts: Receiving two-byte int values over serial

texts:
I am using Python smbus write_word_data method to send int values from a Raspberry Pi to an Arduino using I²C.

This seems to be the correct method.

When I send values from 0-255, I see the following in my Arduino serial monitor

  0,0,0
  0,1,0
  0,2,0
  …
  0,255,0

Sending 256 I see:

  0,0,1

For 257 I see:

  0,1,1

Etc, etc...

My question is, how would I modify the following Arduino code to properly 'reconstitute' the int values, and then send them back to the RPi?

#include <Wire.h>

#define SLAVE_ADDRESS 0x04
int number = 0;
int state = 0;
bool newData = false;

void setup() {
  pinMode(13, OUTPUT);
  Serial.begin(9600);
  // initialize i2c as slave
  Wire.begin(SLAVE_ADDRESS);
  // define callbacks for i2c communication
  Wire.onReceive(receiveData);
  Wire.onRequest(sendData);
  Serial.println("Ready!");
}

void loop() {
  Serial.println(receivedValue);
  newData=false;
}

// callback for received data
void receiveData(int byteCount) {
  while(Wire.available()) {
    newData = true;
    Wire.read();
    if(Wire.available() == 2) {
      receivedValue = Wire.read() | Wire.read() << 8;
    }
  }
}

// callback for sending data
void sendData() {
  Wire.write(number);
}


texts: Can anyone find out why when I run this code for a GPS and BME680 sensor I have no errors but nothing happens

texts:
Here is the code
#include <Wire.h>
#include <SPI.h>
#include <Adafruit_Sensor.h>
#include "Adafruit_BME680.h"
#include <SoftwareSerial.h>

#define BME_SCK 13
#define BME_MISO 12
#define BME_MOSI 11
#define BME_CS 10

#define SEALEVELPRESSURE_HPA (1013.25)

Adafruit_BME680 bme; // I2C
//Adafruit_BME680 bme(BME_CS); // hardware SPI
//Adafruit_BME680 bme(BME_CS, BME_MOSI, BME_MISO,  BME_SCK);

SoftwareSerial gpsSerial(5, 11); // RX, TX (TX not used)
const int sentenceSize = 80;
char sentence[sentenceSize];

void setup() {
  Serial.begin(9600);
  while (!Serial);
  Serial.println(F("BME680 test"));
  gpsSerial.begin(9600);

  if (!bme.begin()) {
    Serial.println("Could not find a valid BME680 sensor, check wiring!");
    while (1);
  }

  // Set up oversampling and filter initialization
  bme.setTemperatureOversampling(BME680_OS_8X);
  bme.setHumidityOversampling(BME680_OS_2X);
  bme.setPressureOversampling(BME680_OS_4X);
  bme.setIIRFilterSize(BME680_FILTER_SIZE_3);
  bme.setGasHeater(320, 150); // 320*C for 150 ms
}

void loop() {

 static int i = 0;
  if (gpsSerial.available())
  {
    char ch = gpsSerial.read();
    if (ch != '\n' && i < sentenceSize)
    {
      sentence[i] = ch;
      i++;
    }
    else
    {
     sentence[i] = '\0';
     i = 0;
     displayGPS();
    }
  }
}

void displayGPS()
{
  char field[20];
  getField(field, 0);
  if (strcmp(field, "$GPRMC") == 0)
  {
    Serial.print("Lat: ");
    getField(field, 3);  // number
    Serial.print(field);
    getField(field, 4); // N/S
    Serial.print(field);

    Serial.print(" Long: ");
    getField(field, 5);  // number
    Serial.print(field);
    getField(field, 6);  // E/W
    Serial.println(field);
  }
}

void getField(char* buffer, int index)
{
  int sentencePos = 0;
  int fieldPos = 0;
  int commaCount = 0;
  while (sentencePos < sentenceSize)
  {
    if (sentence[sentencePos] == ',')
    {
      commaCount ++;
      sentencePos ++;
    }
    if (commaCount == index)
    {
      buffer[fieldPos] = sentence[sentencePos];
      fieldPos ++;
    }
    sentencePos ++;
  }
  buffer[fieldPos] = '\0';

  if (! bme.performReading()) {
    Serial.println("Failed to perform reading :(");
    return;
  }
  Serial.print("Temperature = ");
  Serial.print(bme.temperature);
  Serial.println(" *C");

  Serial.print("Pressure = ");
  Serial.print(bme.pressure / 100.0);
  Serial.println(" hPa");

  Serial.print("Humidity = ");
  Serial.print(bme.humidity);
  Serial.println(" %");

  Serial.print("Gas = ");
  Serial.print(bme.gas_resistance / 1000.0);
  Serial.println(" KOhms");

  Serial.print("Approx. Altitude = ");
  Serial.print(bme.readAltitude(SEALEVELPRESSURE_HPA));
  Serial.println(" m");

  Serial.println();
  delay(2000);
}


texts: Arduino uno board not detected when connected via USB no matter what OS

texts:
I was working with Arduino in Win 8.1, when suddenly it stopped work. I tried to reinstall the drivers and IDE several times, but it didn't solved.

In Win 8.1, when I plug the arduino, I get the pop up message:

USB Device Not Recognized in Windows

Also, when I try to upload a sketch, I get this error in Arduino IDE:

avrdude: ser_open(): can't open device "\\.\com5": the system cannot find the file specified

I switched to Linux (Debian Jessie 64 bits), but it also doesn't get recognized, and I getting the same error, only the port Is different.

I am guessing is a problem with avr, but I don't know what can I do about it.

Other  symptoms:

In both systems the port tool in IDE is grey, so I can't choose a port.
When I press the reset button in Arduino, nothing happens.
The led L (13) is constantly shinning. It never blinks or stops.

Solutions I tried:

Reinstall drivers
Modify the preferences.txt file to change the COM port
Fall back to a previous IDE version
Change the usb cable


texts: Serial.Write(buf,Len) how to read Serial sended array of byte

texts:
hello i'm trying to send array of byte with Serial.Write(buf,Len) but don't know hot to read this code with receiver.

SENDER code:

byte buf[4]={1,2,3,4};
void setup(){
Serial.begin(250000);
}

void loop(){
Serial.write(buf,4);
}

RECEIVER code (WRONG)

byte buf[4];

void setup() {
  Serial.begin(250000); // how suggest

}

void loop() {
  int i = 0;

  if (Serial.available()) {
    Serial.readBytes(buf,4);
    Serial.print(buf[0]);
    Serial.print(buf[1]);
    Serial.print(buf[2]);
    Serial.print(buf[3]);
  }
}

How to receive this ??


texts: Uno with LCD acting strangely - power issue?

texts:
I've got a Uno (Elegoo UNO R3) running with
- Ethernet shield (Kuman K15),
- 4 relay board (Elegoo 4 Channel DC 5V Relay Module with Optocoupler )
- Matrix Orbital 2041 LCD connected via I2C (11mA typical, 90mA with backlight)
- A series of buttons connected

The Uno is currently running plugged in via USB to my macbook pro.

All of these devices are powered by the 5V pin on the Arduino.

The LCD goes wonky from time to time, and other times will work fine, it starts flashing the backlight, and just behaves oddly, sometimes even rebooting, when buttons are pushed (which activate the relays).

I'm wondering if this a power issue, perhaps the Uno isn't able to supply enough current to run everything.

My reading indicates that the USB port should be able to provide ~400mA, and when on an external supply I should able to draw 900 mA when using an external power adapter.  However even with on an external supply (12v, 2A) I still have these issues.

Any thoughts would be much appreciated.
Thanks


texts:
I'm playing with the Arduino Leonardo Keyboard.print() command, but I'm facing a annoying problem:

When I print a double quote, it will not appear and also will make to disappear the next character (i.e.):

Keyboard.print("echo \"This is a demo\"");

Output:

echo his is a demo

And when I use this line:

Keyboard.print("echo -This is \"a demo-");

Output (note the umlaut over the a instead of getting "a):

echo 'This is ä demo'

I suspect that the problem is that my computer is configured to use Spanish layout.

What source code file can I change to fix this? I can't find the defines used by Keyboard.print()


texts: ESPAsyncWebServer how do you escape the % character?

texts: % characters are used for template processing but I want it to just send the % through. How do you tell it to do that?


texts:
I am intending to show the initial, searching for signal..., screen until the location is updated and then show the location on the lcd. However, even after the led on the gps indicates a satellite fix, the screen never leaves the searching for signal screen. Any help would be greatly appreciated-- very new to microcontroller programming. Sorry for the poorly formatted code block as well, I am in a rush.
Thanks in advance.

#include <SoftwareSerial.h>
#include <LiquidCrystal.h>
#include <TinyGPS++.h>

#define RXPin 2
#define TXPin 3
#define GPSBaud 4800

SoftwareSerial ss(RXPin, TXPin);
TinyGPSPlus gps;
LiquidCrystal lcd(12, 11, 10, 7, 6, 5, 4);

double latt;
double lon;
int screen;

void setup(void);
void loop(void);
void readGPS(void);
void update(void);
void render(void);

void setup() {
     //variable initialization
     latt = 0.0;
     lon = 0.0;
     screen = 0;

     //lcd initial setup
     pinMode(9, OUTPUT);
     analogWrite(9, 100);
     pinMode(13, OUTPUT);
     digitalWrite(13, HIGH);

     //display intial screen
     lcd.begin(16,2);
     lcd.clear();
     lcd.setCursor(0,0);
     lcd.print("Searching for");
     lcd.setCursor(6,2);
     lcd.print("Signal ...");
     ss.begin(GPSBaud);
}

void loop() {
    readGPS();
    update();
}

/** Receives data from the gps if available */
void readGPS() {
    while (ss.available() > 0) {
        gps.encode(ss.read());
    }
}

/** Processes the data read by readGPS() */
void update() {
    if (gps.location.isUpdated()) {
        latt = gps.location.lat();
        lon = gps.location.lng();
        render();
    }
}

/** Displays the current screen on the lcd */
void render() {
    if (screen == 0) {
        lcd.clear();
        lcd.setCursor(0,0);
        lcd.print("Lat:");
        lcd.print(latt);
        lcd.print(" Lng:");
        lcd.print(lon);
        lcd.setCursor(0,1);
        lcd.print("Sats:");
        lcd.print(gps.satellites.value());
    }
}


texts: FatalError('Invalid head of packet (0x%s)' % hexify(b)) while uploading on ESP8266

texts:
I have this error while uploading my code to ESP8266 despite the fact that the code runs without errors. I have the git version of installation for the board.

ERROR:

File"C:/../../AppData/Local/Arduino15/packages/esp8266/hardware/esp8266/2.5.2/tools/esptool\esptool.py", line 1889, in slip_reader
raise FatalError('Invalid head of packet (0x%s)' % hexify(b))
esptool.FatalError: Invalid head of packet (0x46)
esptool.FatalError: Invalid head of packet (0x46)

Any help with this? Thanks.


texts: How to detect if running Arduino or bare Atmega328p?

texts:
I'm building something that will mostly run on bare ATmega328p at 8 MHz (as described eg. here), but sometimes I need to run the same code on an Arduino.

I need to initialize the DHT library depending on the clock frequency. For simplicity, I'd rather detect the running environment runtime, in the program itself.

So, is there a straightforward way to detect the clock speed (from fuses?) or some other difference between a stock UNO board and a bare ATmega328p using the internal 8 MHz clock?


texts:
I am using an encoder motor for one of my projects and i was reading encoder values manually through Arduino. It was working fine when i turned it slowly, but whenever i would rotate it at some higher speed, data input to the arduino would stop. I am using the encoder at 4 x.

Can somebody help me with some code to read the data from encoder faster.

    int pulses, A_SIG=0, B_SIG=1;

void setup(){
  attachInterrupt(0, A_RISE, RISING);
  attachInterrupt(1, B_RISE, RISING);
  Serial.begin(115200);
}//setup

void loop(){

}

void A_RISE(){
 detachInterrupt(0);
 A_SIG=1;

 if(B_SIG==0)
  pulses++;//moving forward
 if(B_SIG==1)
  pulses--;//moving reverse
 Serial.println(pulses);
 attachInterrupt(0, A_FALL, FALLING);
}

void A_FALL(){
  detachInterrupt(0);
 A_SIG=0;

 if(B_SIG==1)
    pulses++;//moving forward
 if(B_SIG==0)
     pulses--;//moving reverse
 Serial.println(pulses);
 attachInterrupt(0, A_RISE, RISING);
}

void B_RISE(){
  detachInterrupt(1);
  B_SIG=1;

  if(A_SIG==1)
     pulses++;//moving forward
  if(A_SIG==0)
      pulses--;//moving reverse
  Serial.println(pulses);
  attachInterrupt(1, B_FALL, FALLING);
}

 void B_FALL(){
    detachInterrupt(1);
    B_SIG=0;

    if(A_SIG==0)
       pulses++;//moving forward
    if(A_SIG==1)
       pulses--;//moving reverse
    Serial.println(pulses);
    attachInterrupt(1, B_RISE, RISING);
}