body:
I am using an Arduino Atmega2560 clone, I have used it many times before with satisfactory results - although I haven't used it with my Rpi before.

My Raspberry Pi is model 4 (B I think?).
```c++
#define knap 49
#define motorOutput 8

void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
  pinMode(knap, INPUT);
  pinMode(motorOutput, OUTPUT);
  digitalWrite(motorOutput, LOW);
}

void loop() {
  // put your main code here, to run repeatedly:
  int knapSensor = digitalRead(knap);
  Serial.print(knapSensor);
  if (knapSensor == 1) {
    int knapSensor = digitalRead(knap);
    Serial.print("aktiveret");
    digitalWrite(motorOutput, HIGH);
    delay(500);
    digitalWrite(motorOutput, LOW);
  }
}
```

Now I have double checked, the motor and the button is wired correctly. There is no hardware issue, aside from the cables being sh- quality.

Problem is, whenever I run this program two things will happen;

Either it starts fine by displaying "0000..." on the serial monitor.

Then when I press the button it goes to
"AktiveretAktiveretAktiveret..." even when I depress the button.

Or, it will just display "AktiveretAktiveretAktiveret...".

In either case the motor won't work.

Once again, I have done tests where I have removed the power from the breadboard and replaced the voltage pin for the motor with the voltage pin leading from the button.

First thing didn't change the input (i.e still "AktiveretAktiveret,") the latter started the motor.

I.e this isn't about bad wiring.

EDIT:

Added schematics and changed the code

[![enter image description here][1]][1]

  [1]: https://i.stack.imgur.com/nLmBu.png

title: Rasberry Pi Controlling Arduino - Reads "Ghost" Input - Doesn't Complete Logic Loop

Answers: 2

body:
What motor are you using? If it works straight from the 5v but not from a GPIO, it could be an issue of insufficient power.

As @StarCat4 mentioned, you also need to add a digitalRead inside your while loop if you want the motor to ever turn off.

body:
Your button needs a pulldown resistor to work reliably.

[See the discussion and solution here][1]

The resistor, with a value of around 10K (but any value between 3K and 20K will probably do), needs to be between the input pin or your Arduino and ground to give it a defined value when the button is released.

Putting a resistor between the Arduino pin and ground will make sure the pin reads "low" when no button is pressed. When the button is pressed, it will be connected directly to +5V and will read high. Only a small current (0.5mA) will flow from +5V to ground through the 10K Ohm resistor in that case. It will not create a short circuit.

  [1]: https://forum.arduino.cc/index.php?topic=378402.0


body:
I have a SG90. I just want it to spin 360° and stop, that's about it. This seems impossible.

I have tried the sweep example:

```/* Sweep
 by BARRAGAN <http://barraganstudio.com>
 This example code is in the public domain.

 modified 8 Nov 2013
 by Scott Fitzgerald
 http://www.arduino.cc/en/Tutorial/Sweep
*/

#include <Servo.h>

Servo myservo;  // create servo object to control a servo
// twelve servo objects can be created on most boards

int pos = 0;    // variable to store the servo position

void setup() {
  myservo.attach(9);  // attaches the servo on pin 9 to the servo object
}

void loop() {
  for (pos = 0; pos <= 180; pos += 1) { // goes from 0 degrees to 180 degrees
    // in steps of 1 degree
    myservo.write(pos);              // tell servo to go to position in variable 'pos'
    delay(15);                       // waits 15ms for the servo to reach the position
  }
  for (pos = 180; pos >= 0; pos -= 1) { // goes from 180 degrees to 0 degrees
    myservo.write(pos);              // tell servo to go to position in variable 'pos'
    delay(15);                       // waits 15ms for the servo to reach the position
  }
}

```

This works fine.

I read somewhere that for 360 motors the variable in `myservo.write()` is actually just the speed. So I tried:

```
void loop() {
    myservo.write(0);              // tell servo to go to position in variable 'pos'
    delay(2000);                       // waits 15ms for the servo to reach the position
    myservo.write(180);              // tell servo to go to position in variable 'pos'
    delay(2000);
    myservo.write(0);              // tell servo to go to position in variable 'pos'
}
```
The motor rotates several times then spins the other direction and repeats doing this.

What do I need to do to make it complete 1 rotation and stop?

title: Can't stop SG90 spinning

Answers: 2

body:
TL;DR: *Can't be done.*

On a servo modified for continuous rotation, the signal you send sets direction and speed, *not* rotation angle. You *can* stop it, but you *can't* set an angle.

The sweep example will turn a continuous rotation servo in both directions, but I doubt it hits the angles you send it; it will just adjust speed and direction.

Without external hardware and feedback, like a limit switch, or a rotary encoder, there is no way of knowing what angle the servo is at, and no way to rotate to exactly 360° other than experimenting and "guessing" based on time and rotation speed.

You can then stop it by setting it to the PWM value for 90° or center position, which should set the rotation speed to 0.

On a servo, you can't have both continuous rotation with a set speed, and a set angle of rotation, without extra hardware.

Maybe a stepper motor would be a better choice for your application, or a "normal" servo with a gear that gives you the required rotation range.

body:
A value near 90 will make your rotating servo stop. Try 89, 91 etc. until you find it.

If you are running an auger, use a microswitch that pulses once per revolution. Starting at the point where the switch makes contact, run the servo until the switch opens and closes again then stop. You have made one revolution.


body:
I have already connected succesfully the rfm69 on my Feather M0 Express... but I cannot do it again.

The connections are (in the order of the rfm69):
<pre>
Vin -> 3V
Gnd -> Gnd
En  -> (nothing)
G0  -> 9
SCK -> SCK
MISO -> MI
MOSI -> MO
CS  -> 10
RST -> 6
</pre>
The code of the setup is
```c++
#include <SPI.h>
#include <RH_RF69.h>

#define RFM69_CS      10
#define RFM69_INT     9
#define RFM69_RST     6
#define LED           13

// Singleton instance of the radio driver
RH_RF69 rf69(RFM69_CS, RFM69_INT);

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

  Serial.println("Feather RFM69 RX Test!");
  Serial.println();

  // manual reset
  digitalWrite(RFM69_RST, HIGH);
  delay(10);
  digitalWrite(RFM69_RST, LOW);
  delay(10);

  if (!rf69.init())
    //***********************************
    Serial.println("init failed");
  else
    Serial.println("init ok");

  // Defaults after init are 434.0MHz, modulation GFSK_Rb250Fd250, +13dbM (for low power module)
  // No encryption
  if (!rf69.setFrequency(434.0))
    Serial.println("setFrequency failed");
  else
    Serial.println("setFrequency ok");

  // If you are using a high power RF69 eg RFM69HW, you *must* set a Tx power with the
  // ishighpowermodule flag set like this:
  //rf69.setTxPower(14, true);

  // The encryption key has to be the same as the one in the client
  uint8_t key[] = { 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08,
                    0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08};
  rf69.setEncryptionKey(key);

#if 0
  // For compat with RFM69 Struct_send
  rf69.setModemConfig(RH_RF69::GFSK_Rb250Fd250);
  rf69.setPreambleLength(3);
  uint8_t syncwords[] = { 0x2d, 0x64 };
  rf69.setSyncWords(syncwords, sizeof(syncwords));
  rf69.setEncryptionKey((uint8_t*)"thisIsEncryptKey");
#endif
  Serial.println("Fin du Setup");
}
```
But during the execution, the program stops at `//**************************`
I do not understand.

Can somebody help me?

Thanks a lot and merry Xmas

title: rfm69 on M0 Express... init() doesn't work

Answers: 1

body:
The "init failed" do not appear. Everything stops at "//******".
I have compared to another RFM69 program.
I have added a line " digitalWrite(RFM69_RST, LOW);" at the begining of the "//manual reset" and it works now.
the sequence
  digitalWrite(RFM69_RST, LOW);
  digitalWrite(RFM69_RST, HIGH);
  delay(10);
  digitalWrite(RFM69_RST, LOW);
seems to be more efficient.
... it remains a few mysteriuos for me.

Thank you


body:
I have this code which provides an erroneous unsigned long number.

CODE:
```c++
char buff[100];

int unsigned long bytes;

bytes = 48 * 70 * 144;

sprintf(buff,"%lu bytes\n", bytes);

BTPort.print(buff);
```

OUTPUT:
20088 bytes

BUT: The correct value is 483840

title: Problems in calculating and printing long unsigned integers

Answers: 1

body:
This is because the default numeric type is `int`, which on Arduino is just 16 bits (and signed).

So 48 * 70 * 144 is 0x76200 in hex, which truncated to 16 bits is 0x6200, or 25088. This calculation is done by the preprocessor, not the compiler, so doesn't know (or care) about the destination variable type.

You need to force the values to be calculated as unsigned long by appending `UL` to them:

```c++
bytes = 48UL * 70UL * 144UL;
```


body:
I'm using a seeeduino V4.0 and a CAN-BUS shield v2.0 with industrial grade SD card.

I'm using the default library [given by the wiki of seeed](https://wiki.seeedstudio.com/CAN-BUS_Shield_V2.0/).

I've simulate a can bus with two mcp2515. I can read it without trouble and everything is fine.

I can write/read on the SD card with the exemple given in the SD library.

But when I use this [example](https://github.com/Seeed-Studio/Seeed_Arduino_CAN/blob/master/examples/recv_sd/recv_sd.ino), the can bus and SD card start without error. The can bus read normally and show the can bus data. But when I read the SD card, the file is created but completly empty.
I've tried to modify to write on a .txt instead of .csv and when I try a
```
myFile = SD.open("test.txt", FILE_WRITE);
if (myFile)
{
  ...
}
else
{
  Serial.println("error: file not reachable");
}
```
The "*myFile*" return false.

ps: I don't ask a lot of question here. Sorry for bad formating my question.

title: seeeduino can-bus shield v2: can't read can bus and write on SD card

Answers: 1

body:
Despite the "the library example must be correct, It's work for other people before you", I'm not sure a lot of people make it works.

I've seen that even when the mcp2551 don't receive anything on can bus, the SPI bus is saturated by the mcp2551.

The solution was to use a simplest library make for 8MHz cristal chip. Modify it to works with standard 16MHz and use the interrupt pin (pin 2 on board) as interrupt.

If anybody got the same issue, just post a comment here and I'll do a better and more complete response.

Thank you very much @Timemage for your help


body:
I am working on a project at school that need using ESP8266, but when i compile and run, the code run sucessful but print nothing, when i push the reset button on the ESP8266, it print some garbage output, i tried to reset it many times but it's still the same. I had success in running the code at the first time, but when i build it again, it's just showing garbage output

```
#include <ESP8266WiFi.h>
#include <DNSServer.h>
#include <ESP8266WebServer.h>
#include <Ticker.h> //for LED status
#include <WiFiManager.h>
#include <String.h>
#include "ThingSpeak.h"
#include <PubSubClient.h>
#include <SoftwareSerial.h>
Ticker ticker;

//MQTT - mosquitto

WiFiClient espClient;
PubSubClient client(espClient);
long lastMsg = 0;
char msg[50];
int value = 0;

const char* mqtt_server = "broker.mqtt-dashboard.com";

unsigned long myChannelNumber = 1260973;
const char * myWriteAPIKey = "ML0AX95ICWN71XKC";
const char * myReadAPIKey = "MT8FRNAUN4GJL8F5";

//Ultra Sonic Sensor
const int trig_pin = 5;
const int echo_pin = 4;

//Light Sensor
const int light_sensor = 0;

//LED for tree
const int led_tree = 2;

//LED for remaining water
const int led_red = 14;
const int led_yellow = 12;
const int led_green = 13;

//Soil Moisture Sensor
const int soil_moisture = A0;
int Soil_Value;
int limit = 300;

//Relay
int relay_pin = 15;

float getDistance(){
  float duration, distanceCm;

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

  duration = pulseIn(echo_pin, HIGH);

  distanceCm = duration * 0.034 / 2;

  return distanceCm;
}

//gets called when WiFiManager enters configuration mode
void configModeCallback (WiFiManager *myWiFiManager) {
  Serial.println("Entered config mode");
  Serial.println(WiFi.softAPIP());
  //if you used auto generated SSID, print it
  Serial.println(myWiFiManager->getConfigPortalSSID());
}

void reconnect() {
  // Loop until we're reconnected
  while (!client.connected()) {
    Serial.print("Attempting MQTT connection...");
    // Create a random client ID
    String clientId = "ESP8266Client-";
    clientId += String(random(0xffff), HEX);
    // Attempt to connect
    if (client.connect(clientId.c_str())) {
      Serial.println("connected");
      client.subscribe("LED_tree");
      client.subscribe("Pump_water");
    } else {
      Serial.print("failed, rc=");
      Serial.print(client.state());
      Serial.println(" try again in 5 seconds");
      // Wait 5 seconds before retrying
      delay(5000);
    }
  }
}

void callback(char* topic, byte* payload, unsigned int length) {
  if (topic == "LED_tree"){
    if (digitalRead(led_tree) == HIGH)
      digitalWrite(led_tree, LOW);
    else
      digitalWrite(led_tree, HIGH);
    }
  else if (topic == "Pump_water") {
      Serial.println("pump_water");
    }
  }

void setup() {
  // put your setup code here, to run once:
//  pinMode(LED_BUILTIN, OUTPUT);
  Serial.begin(115200);
  // Ultra Sonic Sensor
  pinMode(trig_pin, OUTPUT);
  pinMode(echo_pin, INPUT);
  // Led for tree
  pinMode(led_tree, OUTPUT);
  // Light Sensor
  pinMode(light_sensor, INPUT);
  // Relay
  pinMode(relay_pin, OUTPUT);
  //led for showing remain water
  pinMode(led_red, OUTPUT);
  pinMode(led_yellow, OUTPUT);
  pinMode(led_green, OUTPUT);
  ThingSpeak.begin(espClient);
  client.setServer(mqtt_server, 1883);
  client.setCallback(callback);

  WiFi.mode(WIFI_STA); // explicitly set mode, esp defaults to STA+AP
  // put your setup code here, to run once:

  //WiFiManager
  //Local intialization. Once its business is done, there is no need to keep it around
  WiFiManager wm;
  //reset settings - for testing
  wm.resetSettings();

  //set callback that gets called when connecting to previous WiFi fails, and enters Access Point mode
  wm.setAPCallback(configModeCallback);

  //fetches ssid and pass and tries to connect
  //if it does not connect it starts an access point with the specified name
  //here  "AutoConnectAP"
  //and goes into a blocking loop awaiting configuration
  if (!wm.autoConnect()) {
    Serial.println("failed to connect and hit timeout");
    //reset and try again, or maybe put it to deep sleep
    ESP.restart();
    delay(1000);
  }

  //if you get here you have connected to the WiFi
  Serial.println("connected...yeey :)");
}

float waterRemaining(int distance) {
  float r = 2;
  float h = 5;
  float V = 3.14*r*r*(h - distance);
  return V;
}

void loop() {
  // put your main code here, to run repeatedly:
  float distance = getDistance();
  float light = digitalRead(light_sensor);
  String light_value;
  if (light == 1){
    light_value = "The light is enough for tree";
  }
  else {
    light_value = "The light is not enough for tree, suggesting turn on the LED";
  }
  float led_status = digitalRead(led_tree);
  float soil = analogRead(soil_moisture);
  float soil_percent = map(soil, 0, 1023, 0, 100);
  float water_remain = waterRemaining(distance);

  //Write data to field
  ThingSpeak.setField(1, distance);
  ThingSpeak.setField(2, light);

  int returncode = ThingSpeak.writeFields(myChannelNumber, myWriteAPIKey);
  // Check return Code
  if (returncode == 200) {
    Serial.println("Channel update sucessful.");
  }
  else {
    Serial.println("Problem updating channel. HTTP error code " + String(returncode));
  }

  //Read data from ThingSpeak
  float Distance2 = ThingSpeak.readIntField(myChannelNumber, 1, myReadAPIKey);
  float Light2 = ThingSpeak.readIntField(myChannelNumber, 2, myReadAPIKey);
  // LED for showing remaining water

  float h_box = 20;
  float res = h_box - distance;

  if (res < 5)
  {
    digitalWrite(led_red, HIGH);
    digitalWrite(led_yellow, LOW);
    digitalWrite(led_green, LOW);
  }
  else if (5 <= res <= 10)
  {
    digitalWrite(led_yellow, HIGH);
    digitalWrite(led_green, LOW);
    digitalWrite(led_red, LOW);
  }
  else if (res > 10)
  {
    digitalWrite(led_green, HIGH);
    digitalWrite(led_red, LOW);
    digitalWrite(led_yellow, LOW);
  }
  // Relay pump water
  if (soil_percent < 60)
  {
    digitalWrite(relay_pin, HIGH);
    delay(3000);
    digitalWrite(relay_pin, LOW);
  }

  Serial.print("Distance: ");
  Serial.println(res);
  if (digitalRead(light_sensor) == 1)
  {
    digitalWrite(led_tree, HIGH);
    Serial.println("Light Sensor: HIGH");
    Serial.println(digitalRead(light_sensor));
  }
  else if (digitalRead(light_sensor) == 0)
  {
    digitalWrite(led_tree, LOW);
    Serial.println("Light Sensor: LOW");
    Serial.println(digitalRead(light_sensor));
  }

   if (!client.connected()) {
    reconnect();
  }
  client.loop();
  client.publish("soil_moisture", String(soil_percent).c_str());
  client.publish("water_remain", String(water_remain).c_str());
  client.publish("light_sensor", String(light_value).c_str());
  delay(2000);
}
```

title: ESP8266 print garbage output

Answers: 0


body:
I have modded a cheap drone controller to output its joystick values to an Arduino Nano.

I made it to output its 4 pot values using I2C to another Arduino don't ask why. So my problem is that I need to send 4 values but I can send only 1. Help me please.

I don't have a time limit or something so I don't need this quick or now!

I am also using a 16x2 LCD without I2C to show the live values and sometime I want to make a menu there or stuff like that.

I would like if you wrote the code for me but its ok if you cant. Also I'm kind of a noob at arduino programming.

Master(a.k.a the nano in the controller):
```c++
int pot1 = A0;
int pot2 = A1;
int pot3 = A2;
int pot4 = A3;

int potValue1 = 0;
int potValue2 = 0;
int potValue3 = 0;
int potValue4 = 0;

int led = 10;
int button = 8;

int lastButtonState;    // the previous state of button
int currentButtonState; // the current state of button

int output1 = A4;
int output2 = A5;
int output3 = A6;
int output4 = A7;

#include <Wire.h>
#include <LiquidCrystal.h> // includes the LiquidCrystal Library

LiquidCrystal lcd(2, 3, 4, 5, 6, 7); // Creates an LC object. Parameters: (rs, enable, d4, d5, d6, d7)

#define SLAVE_ADDR 9

void setup() {
  pinMode(led, OUTPUT);
  pinMode(button, INPUT_PULLUP);

  // Open serial communications and wait for port to open:
  Wire.begin();

  lcd.begin(16, 2);
  lcd.print("   ArduinoTX");
  digitalWrite(led, HIGH);
  delay(600);
  digitalWrite(led, LOW);
  delay(600);
  digitalWrite(led, HIGH);
  delay(600);
  digitalWrite(led, LOW);
  delay(600);
  digitalWrite(led, HIGH);
  delay(600);
  delay(3000);
  lcd.clear();
}

void loop() {
  currentButtonState = digitalRead(button);
  potValue1 = analogRead(pot1);
  potValue2 = analogRead(pot2);
  potValue3 = analogRead(pot3);
  potValue4 = analogRead(pot4);

  int sendValue = map(potValue4, 1, 1023, 1, 255);  //converting to values 255 max
  int sendValue2 = map(potValue3, 1, 1023, 1, 255);
  int sendValue3 = map(potValue2, 1, 1023, 1, 255);
  int sendValue4 = map(potValue1, 1, 1023, 1, 255);

  Wire.beginTransmission(SLAVE_ADDR); //sending only one pot value
  Wire.write(sendValue);
  Wire.endTransmission();

  lastButtonState  = currentButtonState;      // save the last state
  currentButtonState = digitalRead(button); // read new state

  if (lastButtonState == LOW && currentButtonState == LOW) { //dont worry about this
    lcd.print(potValue4);
    lcd.print("        ");
    lcd.print(potValue2);
    delay(delayTime);
    lcd.clear();
    lcd.setCursor(0, 2);
    lcd.print(potValue3);
    lcd.print("        ");
    lcd.print(potValue1);
    delay(delayTime);
    lcd.clear();
  }
}
```

Slave(or an uno who receives the values):
```c++
int rd;
int br;

#include <Wire.h>

#define SLAVE_ADDR 9

void setup() {
  // put your setup code here, to run once:
  Wire.begin(SLAVE_ADDR);

  // Function to run when data received from master
  Wire.onReceive(receiveEvent);

  // Setup Serial Monitor
  Serial.begin(9600);
}

void receiveEvent() {
  // read one character from the I2C
  rd = Wire.read();
  Serial.println(rd);
}

void loop() {
  delay(50);
}
```

Thanks!

title: Sending 4 analog values from one arduino to another with I2C

Answers: 1

body:
Why are you limited to sending one value? You can have multiple `Wire.write()` calls in one transmission.

The slave side just needs to know to expect multiple values in order to accommodate. The best way to do this would be to read in values as long as the master is sending them (check out https://www.arduino.cc/en/Reference/WireRead).

Then your master changes from
```
Wire.beginTransmission(SLAVE_ADDR);
Wire.write(sendValue);
Wire.endTransmission();
```

to

```
Wire.beginTransmission(SLAVE_ADDR);
Wire.write(sendValue);
Wire.write(sendValue2);
Wire.write(sendValue3);
Wire.write(sendValue4);
Wire.endTransmission();
```

And the slave `receiveEvent()` becomes

```
int receiveValue;
int receiveValue2;
int receiveValue3;
int receiveValue4;
int index = 0;
while(Wire.available()){
    if(index == 0){ receiveValue = Wire.read(); }
    else if(index == 1) {receiveValue2 = Wire.read(); }
    else if(index == 2) {receiveValue3 = Wire.read(); }
    else if(index == 3) {receiveValue4 = Wire.read(); }
    index++;
}
```

I would also consider using arrays as a way to clean up some of your variables, but making the above changes should accomplish what you want if not as cleanly.


body:
It might be a bit out there, but for a project that I am working on, my word size default is 24bits (3x8-bit), of which the first 8-bits are data and the next 16-bits are data. I would like to transfer it out of the system as fast as possible with minimal calls to the sub-routines. For this I am trying to reduce the number of calls, I have managed to reduce it from 3 to 2, Can I possibly make it 1 call.

 1. My first attempt was to use 3x SPI.transfer() Second was to use 1x

 2. SPI.transfer() and 1x SPI.transfer16()

I would like to know what would be the ideal way to write a SPI.transfer24 function.

title: Updating SPI transfer16 to create Transfer24

Answers: 1

body:
You can't.  The teensy 4.0 has hardware support for 8-bit, 16-bit and 32-bit transfers. Not 24-bit transfers.

But at 600MHz the overhead of making a function call is negligible anyway - certainly compared to the speed of SPI which is at best about 30x slower than the CPU operates at.

If you want high throughput you won't be wanting to use the SPI library anyway, instead you'd be using DMA to transfer your data with minimal CPU intervention.


body:
The PCM library uses pin 11 and the NRF24L01 also uses pin 11. I am using an Arduino nano, and don't know if there is any way to change the pins of either the speaker or the transceiver.
https://github.com/damellis/PCM

title: Conflicting pins between the PCM library and speaker and the NRF24L01

Answers: 1

body:
No, you can't just change pins. Both systems use hardware that is specific to pin 11.

The best you could achieve would be to use a software SPI implementation on other pins to drive the nRF24L01, but that would mean changes to the library you are using to remove the SPI library usage and replace it with your own software SPI implementation.


body:
I am newer to microcontrollers and have my first project I would like to try. I have started to sketch out a basic design and would like feedback on things that I may be missed or over looked. I understand I am new and things are probably not correct or I might miss use terminology, please feel free to correct me in any aspect.

Project Scope- I would like to integrate the MKR Wifi 1010 into Alexa using IoT to have an Alexa command sent to the MKR Wifi 1010 that then pulls in a relay that actuates a 12v solenoid.

Hardware

Power supply 1- FQCMOGU AL-1250, Input 100-240v 1.6a, Output 12v 5a
Power supply 2- Drok 15w DC/DC, Output 5v 3a
Microcontroller- Arduino MKR Wifi 1010
Relay- Songle SRD-05VDC-SL-C
Solenoid Valve- Beduan 12v

Here is a sketch of my original plan. Let me know any safeties/ protections I may have missed, calculations that do not make sense or if there is an easier/ better way. I have not order the hardware yet and want some people better at this than me to check it over before I do.

[![enter image description here][1]][1]

  [1]: https://i.stack.imgur.com/ZHfjK.jpg

title: MKR Wifi 1010 Project Design

Answers: 0


body:
I'm working on a project involving stepper motors. It is important for this project to track the position of these motors, so I decided to buy an optical rotary encoder, specifically an HKT30(HKT3005-C03G-1000B-5E) pictured [here][1]. I've found it difficult to find resources on how to put this together. I've found datasheets, like [this one][2], but it does not seem to be made up of the same components I have. I think I've basically gotten the gist of how one puts this together from google images, but I would like to be pointed in the way of an explicit resource in case I damage my parts.

Additionally, I was hoping for an explanation on the 5 wires (red, green, black, white, and gray), their purpose and how to set one up on a board.

If any clarification or images are needed, I would be happy to provide.

Thank you!

  [1]: https://www.omc-stepperonline.com/image/cache/catalog/encoder/HKT3008-C03G-1000B-5E 1-1000x1000.jpg
  [2]: https://www.omc-stepperonline.com/download/HKT30-32.pdf

title: How to put together an HKT30 optical rotary encoder?

Answers: 1

body:
It's not hard...

* The sensor screws into the screw holes.
* The disc slots into the gap in the sensor
* The case clips on the outside

As to what the wires are, only the datasheet / manual / manufacturer can tell you that. Maybe if you trace them on the sensor board you can work out what is what.


body:
I picked up my Arduino Nano 33 BLE Sense for the first time in a while and ran the classic "Blink" sketch to make sure it was alright. After slight usage, I wanted to play with the onboard LEDs. When I run the following code, the onboard LED does not turn on:

    #define RED 22

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

    void loop() {
        digitalWrite(RED, HIGH);
    }

However, when I run the following code, the onboard LED does turn on and stays on - it doesn't blink:

    #define RED 22

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

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

What's happening? Is my Nano busted?

title: How do I control the onboard LEDs of my Arduino Nano 33 BLE Sense?

Answers: 1

body:
There are 3 LEDS on the Nano 33 BLE:

- A power LED on pin 25 (yes, you can turn off the power LED programmatically);
- A built-in LED on pin 13;
- An RGB LED with red on pin 22, green on pin 23, and blue on pin 24.

In the [variant file][1], they are given names:

```c++
#define PIN_LED     (13u)
#define LED_BUILTIN PIN_LED
#define LEDR        (22u)
#define LEDG        (23u)
#define LEDB        (24u)
#define LED_PWR     (25u)
```

The power LED and the built-in LED are active-high, i.e. you need to set their pin to `HIGH` to turn these LEDs on. **The three LEDs in the RGB LED, however, are active-low.**

This isn't well-documented as far as I know, and some example [code snippets][2] have it wrong too. A quick look at the [schematic][3] helps.

Also, as StarCat mentioned, you need two `delay()`s to make an LED blink.

  [1]: https://github.com/arduino/ArduinoCore-nRF528x-mbedos/blob/master/variants/ARDUINO_NANO33BLE/pins_arduino.h#L50
  [2]: https://create.arduino.cc/editor/arduino_support/b128a04b-ae92-40b3-be19-18bb0cdf3194/preview?embed
  [3]: https://content.arduino.cc/assets/NANO33BLE_V2.0_sch.pdf


body:
I am working on a RGB LED lamp project and this is the schematic for the circuit I managed to come up with.

[![my led lamp circuit][1]][1]

I am planning to integrate a 27V power supply that powers both the Arduino and a Bluetooth HC-05 module, so I calculated the required resistor values as seen on the schematic. Would this design work? Is 27V too much for the Arduino or does the LED setup balance everything out?

EDIT:

I made an attempt to fix my mistakes based on the answers I received here and this is the new schematic:

[![new led lamp circuit][2]][2]

  [1]: https://i.stack.imgur.com/jLFJQ.png
  [2]: https://i.stack.imgur.com/tRcnG.png

This new model would use a 5V power supply instead. Would this fix all issues?

title: Arduino LED lamp circuit

Answers: 1

body:
No. You will destroy the Arduino and the bluetooth module.

Firstly the Arduino needs no more than 20V absolute maximum - recommended no more than 16V.

Secondly a resistor is not a voltage regulator. It can only drop a fixed voltage when you have a fixed current. It only works with LEDs because they are themselves a fixed voltage.

Thirdly an Arduino output cannot power 6 LEDs in series. You get 5V out, but the combined forward voltage of 6 LEDs is between 12 and 18 volts depending on the colour.


body:
I’m trying to connect my D1 mini module and attiny85 USB module together over a data wire, but I don’t know how to do it.

Basically, what I want to do is have the D1 broadcast a hotspot with a web page that when a button is pressed, it sends a signal to the attiny85. The D1 is connected via power wires to the attiny85.

I have the sending signal and web server setup on the D1 but I don’t know how to let the attiny85 receive it.

If it helps, I’m using the wire.h library on the D1

(edit: sorry for inactivity, just haven’t been able to test it)

title: How to connect D1 mini and ATTINY85 over data wire

Answers: 1

body:
[ATTinyCore][1] seems to come with a Wire library implementation presenting [the same interface][2] as you find in other Arduino board packages.  The [damellis package][3] doesn't, so if you've been trying to use that one, I'd suggest switching to ATTinyCore.

To get started you should be able to use the ESP8266-Arduino Wire library's [Master Writer][4] example with ATTinyCore Wire library's [Slave Receiver][5] example.  To be clear, you don't need to get them from github, they should be available in the File/Examples menu.  Because the interface is the same, you may find that it doesn't matter which board from which you take the example.

I don't know that I've ever used this Wire library in ATTinyCore; my only memory of using I2C slave no an ATTiny85 was coding it directly myself, but I expect it works fine.  I may try myself to confirm though.

On the ATTiny85 you'll be using DIP/SOIC pin 7 (PB2) for the SCL signal.  And DIP/SOIC pin 5 (PB0) for the SDA signal.

If I try it myself later I'll update this with more details.

More details
------------
I don't have a D1 mini.  I do have this NodeMCU clone though.  According to the pin maps, the D1 mini's D1 and D2 pins are same as on the NodeMCU, that is GPIO5 an GPIO4 respectively.  I wired it together as shown here:

[![NodeMCU and ATTiny85 connected for I2C][6]][6]

I've drawn some lines on the lower part of the image where the camera angle is bad.  The smaller inset images are just for showing a better angle there.  The yellow and white leads carrying I2C "Wire" data are doctored simply because they went out of frame.

Don't take the "5V" on the ISP cable breakout too literally, that line is at 3.3V (from the NodeMCU 3.3V pin).

ATTiny85 had the following code loaded onto it.  It is just the ATTinyCore slave receiver example with unnecessary comments removed and code to set the LED based on whether it receives a non-zero byte in the I2C ("Wire") transaction:
```c++
#include <Wire.h>

static const int LED_PIN = 4;
static const int SLAVE_ADDRESS = 0x08;

void setup() {
  Wire.begin(SLAVE_ADDRESS);
  Wire.onReceive(wire_receive);
  Serial.begin(9600);
  pinMode(LED_PIN, OUTPUT);
}

void loop() {}

void wire_receive(int howMany) {
  if (Wire.available()) {
    digitalWrite(LED_PIN, Wire.read());
  }
}
```

The following was loaded onto the NodeMCU board.  Likewise derived from the ESP8266 Arduino Wire master-writer example.  Set the local ESP8266 led when it sends the state over to the ATTiny85.  The result is that the ATTiny85 and ESP8266 change their LEDs every 1 second together.  The NodeMCU module is wired to light the LED on a LOW, the ATTiny85 to light on a HIGH, so when one is lit the other is not.

```c++
#include <Wire.h>
#include <PolledTimeout.h>

#define SDA_PIN 4
#define SCL_PIN 5
const int16_t I2C_SLAVE_ADDRESS  = 0x08;

void setup() {
  pinMode(LED_BUILTIN, OUTPUT);
  Wire.begin(SDA_PIN, SCL_PIN);
}

void toggle_led() {
    static bool led_state;

    led_state = !led_state;
    digitalWrite(LED_BUILTIN, led_state);
    Wire.beginTransmission(I2C_SLAVE_ADDRESS);
    Wire.write(led_state);
    Wire.endTransmission();
}

void loop() {
  using periodic = esp8266::polledTimeout::periodicMs;
  static periodic nextPing(1000);

  if (nextPing) {
    toggle_led();
  }
}
```

  [1]: https://github.com/SpenceKonde/ATTinyCore/
  [2]: https://www.arduino.cc/en/Reference/Wire
  [3]: https://github.com/damellis/attiny
  [4]: https://github.com/esp8266/Arduino/blob/2.7.4/libraries/Wire/examples/master_writer/master_writer.ino
  [5]: https://github.com/SpenceKonde/ATTinyCore/blob/1.1.5/libraries/Wire/examples/slave_receiver/slave_receiver.ino
  [6]: https://i.stack.imgur.com/IjKAG.jpg


body:
I am developing a product in which i have to use 5 LCDs. The LCD i am using does not contain CS pin. SO i had to use MUX for muxing of complete SPI bus from one LCD to other.
But the issue i am facing is, LCD turn off display when i change the select lines of MUX to switch the SPI bus to other LCD. sometimes it just show white screen. basically switching the MUX put the LCD in trouble.

what i am thinking is that when i switch the BUS from one LCD to other then MUX may generate some random data during switching or something like that.
so there is any way the before switching, i should put lcd in a mode that it should not update display until i send any special command again ?

All pins except RST are going through mux, i used separate GPIO for RST of every LCD so that RST should not have issues during switching.

Library i am using is TFT_eSPI.h
Basically library do not support mulitple LCDs, so i customized it by just making global variable for reset pin, when i switch the mux to specific LCD then i change the values of RST to corresponding LCD.

My LCD link is
https://megaeshop.pk/1-3-inch-ips-hd-tft-st7789-ic-unit-240-240-spi-communication-3-3v-voltage-spi-interface-full-color-lcd-oled-display.html

Controller is ESP32

MUX 74HC4051

purpose of using LCD without CS is related to pricing issues. LCDs with CS are too expensive.

I am sorry if my Question formating is not correct or i missed any information. pleas feel free to ask.
I think on all the forums and articles, this is first time i am using multiple LCDs without CS :)

title: Getting Trouble in multiple ST7789 SPI LCDs (without CS) with ESP32

Answers: 0


body:
I am using Attiny85 to control 4 LEDs parallelly with a programmable switch. But even though when the LEDs are in OFF state, current consumption is around 7-8mA.
I am using a 200mAh battery in my project and it is draining up the whole battery in 24hrs (when the LEDs are in OFF state)

Below is the schematic image of my attiny85 circuit:
[![Attiny85 circuit][1]][1]

  [1]: https://i.stack.imgur.com/BMBZh.png

Code:
```c++
//Absolute maximum current of each pin of Attiny85 is 40mA
//So each LED has been given to seperate pins

const int buttonPin = 2;    // the pin that the pushbutton is attached to
const int ledPin1 = 0;      // the pin that the White LED1 is attached to
const int ledPin2 = 1;      // the pin that the Blue LED1 is attached to
const int ledPin3 = 3;      // the pin that the White LED2 is attached to
const int ledPin4 = 4;      // the pin that the Blue LED2 is attached to

// Variables will change:
int counter = 1;             // counter for the number of button presses
int buttonState = 0;         // current state of the button
int lastButtonState = 0;     // previous state of the button

void setup() {
  pinMode(buttonPin, INPUT);
  pinMode(ledPin1, OUTPUT);
  pinMode(ledPin2, OUTPUT);
  pinMode(ledPin3, OUTPUT);
  pinMode(ledPin4, OUTPUT);
  //Serial.begin(9600);
}

void loop() {
  buttonState = digitalRead(buttonPin);    // read the pushbutton input pin

  if (buttonState != lastButtonState) {    // compare the buttonState to its previous state
    if (buttonState == HIGH) {             // if the state has changed, increment the counter
      counter++;                           // if the current state is HIGH then the button went from off to on:
    }
    delay(50);                    // Delay a little bit to avoid bouncing
  }

  lastButtonState = buttonState;  // save the current state as the last state for next time through the loop

  if (counter == 2) {
    digitalWrite(ledPin1, HIGH);  //turns on White LED1
    digitalWrite(ledPin2, LOW);
    digitalWrite(ledPin3, LOW);
    digitalWrite(ledPin4, LOW);
  }
  else if (counter == 3) {        //turns on White LED2
    digitalWrite(ledPin1, LOW);
    digitalWrite(ledPin2, LOW);
    digitalWrite(ledPin3, HIGH);
    digitalWrite(ledPin4, LOW);
  }
  else if (counter == 4) {        //turns on both White LEDs
    digitalWrite(ledPin1, HIGH);
    digitalWrite(ledPin2, LOW);
    digitalWrite(ledPin3, HIGH);
    digitalWrite(ledPin4, LOW);
  }
    else if (counter == 5) {        //turns on Blue LED1
    digitalWrite(ledPin1, LOW);
    digitalWrite(ledPin2, HIGH);
    digitalWrite(ledPin3, LOW);
    digitalWrite(ledPin4, LOW);
  }
    else if (counter == 6) {       //turns on Blue LED2
    digitalWrite(ledPin1, LOW);
    digitalWrite(ledPin2, LOW);
    digitalWrite(ledPin3, LOW);
    digitalWrite(ledPin4, HIGH);
  }
  else if (counter >= 7) {         //turns on both Blue LEDs
    digitalWrite(ledPin1, LOW);
    digitalWrite(ledPin2, HIGH);
    digitalWrite(ledPin3, LOW);
    digitalWrite(ledPin4, HIGH);
    counter = 0;
  }
  else if (counter == 1){         // turns off all the LEDs after one button push
    digitalWrite(ledPin1, LOW);
    digitalWrite(ledPin2, LOW);
    digitalWrite(ledPin3, LOW);
    digitalWrite(ledPin4, LOW);
  }
}

```
For each time push button is pressed, respective LEDs get ON and there are 6 such cases. In 7th case, it goes back to case 1.

So, is there a way to reduce the current consumption?

Is there any commands where we can,
1. Reduce the clock frequency
2. Disable all the interrupts
3. Disable all modules etcc.....when not in use

If the current consumption goes less than 1mA that would be great.

title: To reduce the Attiny85 current consumption

Answers: 0


body:
On an ESP8266 I want to create a little webserver that shows me a dashboard with charts and stuff. For this I want to include the [echarts][1]-library as it works offline. To access it the only way I can see this working is that I write:

    const char libData[784674] PROGMEM = "the entire 700 KB library goes here";

And then deliver it on request with `server.on('./echarts.min.js', handleLibRequest)` or something like that.

Now my problem is that in this 700KB of text there are `'` and `"` characters all scattered arround. The C++11 way of `R("hard escapable '"'''" string")` isn't working in my environment. How would one go about this to include this file in my code?

Is there mybe some way utilize the preprocessor for this? Or maybe an online tool that converts `"str" to ['s','t','r']`?

  [1]: https://echarts.apache.org/en/index.html

title: Properly escaping very large strings

Answers: 4

body:
You could write a program that escapes all the offending characters and use the output of that in your `const char libData[]`; see [here][1] for a list of escape sequences;

You could serve the library directly from a (pseudo) file system on the ESP8266, without having to copy it "manually" into a variable; you just copy the file to the filesystem;

You could Base64-encode the library and manually copy the result into `const char libData[]`, then Base64-decode before sending;

What I like to do, if there is no file system but enough memory:

- Gzip the library;
- Base64-encode the .gz file;
- Copy the Base-64 encoded result by hand into your `const char libData[]`.

The Base64 encoding allows you to copy/paste without problems.

Despite the Base64 encoding, the gzipping makes the end result smaller than the original, which helps with memory usage and transfer speed, and it will have no "quote problems".

When the libData needs to be served, Base64-decode it, and send the resulting (gzipped) data to the client; all browsers I know will accept that if you add the `Content-Encoding: gzip` header.

Example code on a raw client without a webserver library: [`unsigned int sendBase64Page()`][2] (mind the content type).

  [1]: https://en.cppreference.com/w/cpp/language/escape
  [2]: https://github.com/ocrdu/arduino-webinterface-websocket-ap/blob/master/apwebsocketserver.ino#L326

body:
I've just written myself now a python-script that creates a char-array with the numbers representing the characters. Maybe it helps someone else:

    import sys

    def arrayify(sourceFile, targetFile):
        with open(sourceFile, 'rb') as sf:
            contents = sf.read()

            charArray = ""

            for char in contents:
                charArray += str(char) + ","

            # end array

            with open(targetFile, 'w') as tf:
                tf.write(charArray)

    if __name__ == "__main__":
        sourceFile = sys.argv[1]
        targetFile = sys.argv[2]

        arrayify(sourceFile, targetFile)

body:
You can use "objcopy" to produce an object file from the file's contents, if you declare it as binary.

    objcopy -I binary echarts.min.js -O <your-bfd-format> echarts.min.js.o

To find out which BFD format you need, run `objdump -t <any object file>` and look at its output.

The resulting object file contains an object named after the input file in the `.data` section. There are 3 symbols in the symbol table:

- _binary_echarts_min_js_start
- _binary_echarts_min_js_end
- _binary_echarts_min_js_size

The "start" symbol marks the beginning of the file's content, and the "end" symbol marks the address **after** the last byte. The "size" symbol is hard to use in C or C++, because it is an absolute value.

Commonly I just use "start" and "end" like this:

```c
extern const char _binary_x_bin_start[];
extern const char _binary_x_bin_end[];
```

body:
Its simple, paste all you page between "()" on the below line

```
const char live_html[] PROGMEM = R"rawliteral(your date here)rawliteral";
```


body:
I'm building an CNC mill with an Arduino UNO with a CNC Shield V3. But I have a problem with the Y motor direction. It only moves in one way while the X motor is moving both ways. When I just installed everything it worked, but after a view tries it doesn't anymore. I viewed multiple topics on this problem but nothing is working.

* I tried to switch the stepper drives but that didn't make a difference.

* Switched the stepper motors and then the x motor moved in one way so it isn't the stepper motor.

* Tried cloning the Y controller to the 4th connection. Also didn't work.

* Tried multiple GRBL HEX files, all the same.

* I also tried multiple gcode senders but is just doesn't make a difference.

Is there anything else that I can try to help this problem? Or shall I order an new shield to test if this shield is broken.

title: CNC Y-axis stepper moving forward but not in opposite direction

Answers: 0


body:
I would like to a build a temperature sensing variable speed fan controller for my truck. Currently using a purchased 2 speed on/off relay based controller, but my fans are overloading the whole circuit when the controller is powered on during a high speed temperature scenario. On low speed, I have the fans wired in series to spin both slower - works great. Each fan initially draws 100 amps at full 12v. On the low speed (6v/series), they cruise about 20a together. On high speed, they settle in around 25a each.

I am somewhat experienced with arduino and using a few references to build in specific features I want, but here is the main example I am going by.
https://circuitdigest.com/microcontroller-projects/automatic-temperature-controlled-fan-project

My question is around the type and size of transistor that I would need to handle the amount of current these fans draw. Some examples have MOSFET while others have FET or even standard PNP. I am pretty new to working with transistors and can't find any references that make sense. Would love to get a reference to learn this calculation and appropriate type.

Edit: removed picture with incorrect wiring diagram.

title: Variable Fan Controller - Properly Sized Transistor

Answers: 1

body:
Doing a quick search for high-current MOSFET transistors, I ran across the following:

https://www.digikey.com/en/products/detail/ixys/IXFK170N20T/2126313

The important spec here is the Rds ON (max) of 11mOhm @ 60A, 10V

At your peak current of 100A, you would drop 1.1V across the transistor, for a power dissipation of 110W.

The advertised P(max) is 1150W, so assuming the junction temp can be held to under 175C (and with an entire metal truck to use for a heat sink, this shouldn't be a problem) you should be OK with this device.  In the 'cruise' configuration with 25A motor current, you should have no problem controlling the fans.

YMMV ;-)


body:
Im a complete beginner

Im making a project using relay modules and arduino. but all the digital pins of my arduino are filled.
I wanted to ask if i can use the analog pins to connect my relay module to my arduino? If yes can anyone give me the statements to write high and low using analog.

title: Can i connect in pin of relay module to Analog pins of arduino instead of digital pin?

Answers: 1

body:
Yes, you can  use the analog pins as digital pins.
Quoting this [Arduino tutorial][1]:

```
pinMode(A0, OUTPUT);
digitalWrite(A0, HIGH);
```

EDIT:

Here is the code snippet for digital input:

```
pinMode(A0, INPUT);
digitalRead(A0);
```

  [1]: https://www.arduino.cc/en/Tutorial/Foundations/AnalogInputPins


body:
I want to monitor an input and then send the information in an encrypted way that can't be easily unlocked even if a malicious actor gets access to the device itself. I'm new to using the Teensy although I have done a few simple things with Arduino microcontrollers. I was hoping to find out if anyone has implemented RSA or other asymmetrical encryption on a Teensy or to figure out if it has enough processing power to make it feasible. I would also accept using other Arduinos (I have an MKR1000 as well), for this but I assume because the Teensy has much better performance it's more likely to be able to do computationally expensive encryption.

This won't need to decrypt anything, it will only be sending data encrypted using the public key of the receiving user.

title: Asymmetric encryption on a Teensy?

Answers: 1

body:
Teensy4.1 has 55 digital IO (serial) pins at up to 200MHz. The USB port supports 480mbps, and ethernet is 10/100mbps. You're limited to 32 DMA channels, though (complicated but these are used to access onboard peripherals/memory). You don't have much contiguous ram, either.

Now, you haven't explained what you're doing with this data. This matters because even though the CPU is running at 600MHz, asymmetric encryption is slow. Are you trying to perform real-time encrypted communication? Are you just sending or receiving data as well?

Nothing stopping you from asymmetrically encrypting on a Teensy. You can find the source code for the OpenSSL functions RSA_public_encrypt and RSA_private_decrypt.
[This question][1] goes into calculating how many CPU cycles are needed to encrypt X bytes of data.

However, asymmetric encryption has problems: Like I said, it's slow - specifically RSA, and the size of the data you can encrypt depends on the size of your key and padding.

If you want to communicate in something resembling real-time, you want to use hybrid encryption. You should read about how TLS works; the short version is that an asymmetric handshake occurs where the two parties agree on a symmetric key. Once you decide what your data actually is, you can quantize it (eg. TLS 'chunks' are up to 16KB which are then sent as multiple TCP packets) then both parties use the symmetric key to send/receive - which can encrypt large data chunks without issue.

  [1]: https://crypto.stackexchange.com/questions/39923/how-to-calculate-time-taken-by-encryption


body:
I have been trying to get an answer my question for a 2 days *already. It's good for knowledge collecting and playing with different things, but there haven't been a solution so far.*

I'm trying to leverage the `HXT500` Servo with the `Fast PWM with a TOP ICR1`

I'm using the `DFRobot DFRduino UNO v3.0 (R3)` analog of the `Arduino UNO`. Based on [the `Atmega 328P-PU`][1]

I have an `Oscilloscope till 5 MHz` as additional tool
## Question ##

 1. Why the `Fast PWM, TOP ISC1` always has the HIGHT only on a oscilloscope
 2. Why the Clock `Prescaler` doesn't work

## My investigations & observations ##

I activated the `PWM with TOP ICR1` but on my oscilloscope showed only a `5V straight line`, I checked different diapasons (horizontal bases) `(1a)`. [Connected to `pins 10 or 9`][2]. I assumed that my UNO works on `1 MHz` (9.2.1 Default Clock Source on Page 37) [and calculated][3] ICR1, OCR1A:B for 0 and 180 degree.

```
     void setup() {
      // all as Ports (for outputs)
     DDRB=0xFF;
     DDRC=0xFF;
     DDRD=0xFF;

      // Table 16-4 on Page 141
      // Fast PWM TOP is ICR1
      TCCR1A|=(0<<WGM10)|(1<<WGM11);
      TCCR1B|=(1<<WGM13)|(1<<WGM12);
      ICR1=2499;

      // Table 16-2 on Page 140
      // Clear OC1A/OC1B on Compare Match, set OC1A/OC1B at BOTTOM (non-inverting mode)
      TCCR1A|=(1<<COM1A1)|(1<<COM1B1);

      // Table 16-5 on Page 143
      // clkI/O/8
      TCCR1B|=(0<<CS12)|(1<<CS11)|(0<<CS10); // (2a)
    }

    void loop() {
      digitalWrite(LED_BUILTIN, HIGH);
        // 90 degree
        OCR1A=299;
        OCR1B=299;
      delay(1000);
      digitalWrite(LED_BUILTIN, LOW);
        // 0 degree
        OCR1A=49;
        OCR1B=49;
      delay(1000);
    }
```
There I noticed the following issues:

 - I tried different `Prescale`s - there weren't any differences `(2a)`
 - I tried 1 MHz, 8 MHz, 16 MHz - straight HIGHT line

What I have tried next:

 - To use an Example for Servo leveraging from Arduino IDE. It worked but as I understood it worked via Interrupts, not a Hardware solution
 - To use Fast PWM, 9 & 10-bit. `(2a) Prescale`s didn't work - I had movement
 - To use Fast PWM, 8-bit (with code adjustment and wrong angles). `(2a) Prescaler`s didn't work - I had movement

  [1]: https://ww1.microchip.com/downloads/en/DeviceDoc/ATmega48A-PA-88A-PA-168A-PA-328-P-DS-DS40002061B.pdf
  [2]: http://arduino.zl3p.com/s_infa/pict/arduino_uno_pins.jpg
  [3]: https://docs.google.com/spreadsheets/d/1HVU97dkSNjiICo6uoFb2yLl0UpHilEODdI35nwU51xE/edit?usp=sharing

title: Always HIGHT line on Oscilloscope when UNO's Fast PWM TOP ICR1

Answers: 1

body:
You might want to set the `TCCR1A` and `TCCR1B` registers to `0` before your code as the [Arduino library sets the WGM10 bit](https://github.com/arduino/ArduinoCore-avr/blob/6ec80154cd2ca52bce443afbbed8a1ad44d049cb/cores/arduino/wiring.c#L305). Or change the first `|=` to a `=`. By leaving the WGM10 bit set, you get fast PWM mode, with TOP set to OCR1A. Combined with your other code, this would result in both pins having a 100% duty cycle.

So use
```
TCCR1A=(0<<WGM10)|(1<<WGM11);
TCCR1B=(1<<WGM13)|(1<<WGM12);
```
or
```
TCCR1A=0;
TCCR1B=0;
TCCR1A|=(0<<WGM10)|(1<<WGM11);
TCCR1B|=(1<<WGM13)|(1<<WGM12);
```
Other than that, you code looks fine, and should give you a 800Hz signal.

PS `"I assumed that my UNO works on 1 MHz"`; no, the UNO runs at 16Mhz.


body:
my project is to control led diode and dc motor, test shield buttons, and check system run time.
Testing buttons and run time i have done.

Deal is with led and dc motor control.
I'm getting phantom reading, that means,when i'm scrolling main menu, diode and dc motor starts working, when they shouldn't.
Dc motor or led diode should work only when i enter their control menu, not when i'm in main menu.

 ```#include <LiquidCrystal.h>
LiquidCrystal lcd(8, 9, 4, 5, 6, 7);

#define btnRIGHT  0
#define btnUP     1
#define btnDOWN   2
#define btnLEFT   3
#define btnSELECT 4
#define btnNONE   5

int masterKey = A0;
int keypadKey = 0;
int buttonPress = 0;

char push;

byte menu = 1;
byte menuOld = 1;
byte menuAll = 4;

//_______LED/MOTOR_________________
int speedall;
int mtor = 5,
    led = 6,
    error = 7;
const int Upstep = 3;
const int maxspeed = 255;

void setup() {
  pinMode(led, OUTPUT);
  pinMode(mtor, OUTPUT);
  lcd.begin(16, 2);
  mainMenu();
  delay(100);
  Serial.begin(9600);
}

void loop()
{
  push = readKeypad();
  menuContr();
  if (push == btnSELECT) //enter selected menu
  {
    waitKey();
    switch (menu) {
      case 1:
        lcd.begin(16, 2);
        lcd.setCursor(0, 0);
        lcd.print("Push the buttons");
        ButtonTest();
        break;
      case 2:
        lcd.clear();
        lcd.setCursor(0, 0);
        lcd.print("Speed 0 to 255:");
        MotorControl();
        break;
      case 3:
        lcd.clear();
        lcd.setCursor(0, 0);
        lcd.print("Brightness 0 to 255:");
        LEDControl();
        break;
      case 4:
        SystemTime();
        break;
    }
    mainMenu();
    waitKey();
  }
  delay(10);
}
//____________________________
void ButtonTest() {
  while (readKeypad() != btnSELECT) {
    lcd.setCursor(9, 1);
    lcd.print(millis() / 1000);
    lcd.setCursor(0, 1);
    int lcd_key = readKeypad();
    switch (lcd_key) {
      case btnRIGHT:
        lcd.print("RIGHT ");
        break;
      case btnLEFT:
        lcd.print("LEFT   ");
        break;
      case btnUP:
        lcd.print("UP    ");
        break;
      case btnDOWN:
        lcd.print("DOWN  ");
        break;
      case btnSELECT:
        lcd.print("SELECT");
        break;
      case btnNONE:
        lcd.print("NONE  ");
        break;
    }
  }
}
//____________________________
void MotorControl() {
  while (readKeypad() !=  btnSELECT) {
    if (readKeypad() == btnUP) {
      speedall <= maxspeed;
      speedall += Upstep;
      lcd.setCursor(5, 2);
      lcd.print("                ");
      lcd.setCursor(5, 2);
      lcd.print(speedall);
      delay(100);
      analogWrite(mtor, speedall);

    }
    else if (readKeypad() == btnDOWN) {
      speedall <= maxspeed;
      speedall -= Upstep;
      Serial.print(speedall);
      lcd.setCursor(5, 2);
      lcd.print("                ");
      lcd.setCursor(5, 2);
      delay(100);
      analogWrite(mtor, speedall);
    }
  }
}
//____________________________
void LEDControl() {

  while (readKeypad() != btnSELECT) {
    if (readKeypad() ==  btnUP) {
      speedall < 255;
      speedall += Upstep;

      lcd.setCursor(5, 2);
      lcd.print("                ");
      lcd.setCursor(5, 2);
      lcd.print(speedall);
      delay(100);
      analogWrite(led, speedall);

    }
    else if (readKeypad() == btnDOWN) {
      speedall > 255;
      speedall -= Upstep;

      lcd.setCursor(5, 2);
      lcd.print("                ");
      lcd.setCursor(5, 2);
      lcd.print(speedall);
      delay(100);
      analogWrite(led, speedall);

    }
  }
}
//____________________________
void SystemTime() {
  lcd.clear();
  while (readKeypad() != btnSELECT) {
    lcd.setCursor(6, 0);
    lcd.print("TIME");
    lcd.setCursor(7, 1);
    lcd.print(millis());
    lcd.print("s");
    delay(100);
    lcd.clear();
  }
}
//______________________________

void mainMenu() {
  lcd.clear();
  lcd.setCursor(0, 0);
  switch (menu) {
    case 1:
      Serial.print(speedall);
      lcd.print("Button test");
      break;
    case 2:
      Serial.print(speedall);
      lcd.print("Motor contr");
      break;
    case 3:
      Serial.print(speedall);
      lcd.print("LED contr");
      break;
    case 4:
      Serial.print(speedall);
      lcd.print("Syst run time");
      break;
  }
}
//____________________________
void executeAction() {
  switch (menu) {
    case 1:
      ButtonTest();
      break;
    case 2:
      MotorControl();
      break;
    case 3:
      LEDControl();
      break;
    case 4:
      SystemTime();
      break;
  }
}
void menuContr() {
  waitKey();
  if (push == btnUP) {
    menu++;
    if (menu > menuAll)
      menu = 1;
  }
  else if (push == btnDOWN) {
    menu--;
    if (menu == 0)
      menu = menuAll;
  }
  if (menu != menuOld) {
    mainMenu();
    menuOld = menu;
  }
}
int readKeypad() {
  keypadKey = analogRead(masterKey);
  if (keypadKey > 1000) return btnNONE;     // about 1023
  if (keypadKey < 50)   return btnRIGHT;    // about 0
  if (keypadKey < 195)  return btnUP;       // about 99
  if (keypadKey < 380)  return btnDOWN;     // about 255
  if (keypadKey < 555)  return btnLEFT;     // about 409
  if (keypadKey < 790)  return btnSELECT;   // about 640
  return btnNONE;
}
void waitKey() {
  while ( analogRead(masterKey) < 800) {}
} ```

title: Phantom reading

Answers: 0


body:
I have a wemos d1 mini. I uploaded a code in wemos d1 mini and after that my wemos mini not working. I tried to upload another code in it even the led blink sketch and even a blank sketch but whenever I tried to do that it just shows connecting but never connects to Arduino ide.[![enter image description here][1]][1]
First of all, whenever I tried to connect it to the computer or power it up, its built-in light stays bright and in the serial monitor, it shows garbage characters continuously. [![enter image description here][2]][2]But when I connect GPIO 0(d3) of wemos mini to the ground and press the reset button it starts the boot mode and when I upload any code it shows connecting but never upload any code here's the code which uploaded first in it.

```cpp
#include <WiFiManager.h>
#include <ESP8266WiFi.h>
#include <ESP8266WebServer.h>
#include <DNSServer.h>
#include <BlynkSimpleEsp8266.h>
BlynkTimer timer;

//Pin assignments
#define switch_1 3 // D5 Pin of NodeMcu
#define switch_2 14 // D6 Pin of NodeMcu
#define switch_3 12 // D7 Pin of NodeMcu
#define switch_4 13
// D0 Pin of NodeMcu
#define button 2
#define relay_1 4 //D1 Pin of NodeMcu
#define relay_2 5 //D2 Pin of NodeMcu
#define relay_3 16 //RX Pin of NodeMcu
#define relay_4 15 //D4 Pin of NodeMcu

#define LED1 1 //D0 Pin of NodeMcu

int MODE = 0;

// Your WiFi credentials.
// Set password to "" for open networks.
char ssid[] = "Android-AP960A";
char pass[] = "talal123";

// You should get Auth Token in the Blynk App.
// Go to the Project Settings (nut icon).
char auth[] = "3ueT9aVLvkL60q8piJ6p5Kxx31zZ5xEC";

int switch_1_ON = 1;
int switch_2_ON = 1;
int switch_3_ON = 1;
int switch_4_ON = 1;

BLYNK_WRITE(V1)
{
int pinValue = param.asInt(); // assigning incoming value from pin V1 to a variable
digitalWrite(relay_1, pinValue); // process received value
}

BLYNK_WRITE(V2)
{
int pinValue = param.asInt(); // assigning incoming value from pin V2 to a variable
digitalWrite(relay_2, pinValue); // process received value
}
BLYNK_WRITE(V3)
{
int pinValue = param.asInt(); // assigning incoming value from pin V1 to a variable
digitalWrite(relay_3, pinValue); // process received value
}

BLYNK_WRITE(V4)
{
int pinValue = param.asInt(); // assigning incoming value from pin V2 to a variable
digitalWrite(relay_4, pinValue); // process received value
}

void internet() //When this device connects with internet
{
//**************************************
//Switch 1 configuration
//**************************************
if (digitalRead(switch_1) == HIGH)
{
if (switch_1_ON == 0 )
{
digitalWrite(relay_1, LOW);
Blynk.virtualWrite(V1, 0);
switch_1_ON = 1;
}
}

if (digitalRead(switch_1) == LOW )
{
if (switch_1_ON == 1)
{
digitalWrite(relay_1, HIGH);
Blynk.virtualWrite(V1, 1);
switch_1_ON = 0;
}
}
//**************************************
//Switch 2 configuration
//**************************************
if (digitalRead(switch_2) == HIGH)
{
if (switch_2_ON == 0 )
{
digitalWrite(relay_2, LOW);
Blynk.virtualWrite(V2, 0);
switch_2_ON = 1;
}
}

if (digitalRead(switch_2) == LOW )
{
if (switch_2_ON == 1)
{
digitalWrite(relay_2, HIGH);
Blynk.virtualWrite(V2, 1);
switch_2_ON = 0;
}
}
//**************************************
//Switch 3 configuration
//**************************************
if (digitalRead(switch_3) == HIGH)
{
if (switch_3_ON == 0 )
{
digitalWrite(relay_1, LOW);
Blynk.virtualWrite(V3, 0);
switch_3_ON = 1;
}
}

if (digitalRead(switch_3) == LOW )
{
if (switch_3_ON == 1)
{
digitalWrite(relay_3, HIGH);
Blynk.virtualWrite(V3, 1);
switch_3_ON = 0;
}
}
//**************************************
//Switch 4 configuration
//**************************************
if (digitalRead(switch_4) == HIGH)
{
if (switch_4_ON == 0 )
{
digitalWrite(relay_4, LOW);
Blynk.virtualWrite(V4, 0);
switch_4_ON = 1;
}
}

if (digitalRead(switch_4) == LOW )
{
if (switch_4_ON == 1)
{
digitalWrite(relay_4, HIGH);
Blynk.virtualWrite(V4, 1);
switch_4_ON = 0;
}
}
}
//********************************************

void no_internet() //When this device doesn't gets internet
{
//**************************************
//Switch 1 configuration
//**************************************
if (digitalRead(switch_1) == HIGH)
{
if (switch_1_ON == 0 )
{
digitalWrite(relay_1, LOW);
switch_1_ON = 1;
}
}

if (digitalRead(switch_1) == LOW )
{
if (switch_1_ON == 1)
{
digitalWrite(relay_1, HIGH);
switch_1_ON = 0;
}
}
//**************************************
//Switch 2 configuration
//**************************************
if (digitalRead(switch_2) == HIGH)
{
if (switch_2_ON == 0 )
{
digitalWrite(relay_2, LOW);
switch_2_ON = 1;
}
}

if (digitalRead(switch_2) == LOW )
{
if (switch_2_ON == 1)
{
digitalWrite(relay_2, HIGH);
switch_2_ON = 0;
}
}
//**************************************
//Switch 3 configuration
//**************************************
if (digitalRead(switch_3) == HIGH)
{
if (switch_3_ON == 0 )
{
digitalWrite(relay_1, LOW);
switch_3_ON = 1;
}
}

if (digitalRead(switch_3) == LOW )
{
if (switch_3_ON == 1)
{
digitalWrite(relay_3, HIGH);
switch_3_ON = 0;
}
}
//**************************************
//Switch 4 configuration
//**************************************
if (digitalRead(switch_4) == HIGH)
{
if (switch_4_ON == 0 )
{
digitalWrite(relay_4, LOW);
switch_4_ON = 1;
}
}

if (digitalRead(switch_4) == LOW )
{
if (switch_4_ON == 1)
{
digitalWrite(relay_4, HIGH);
switch_4_ON = 0;
}
}
}

void Blynk_status() // called every 3 seconds by SimpleTimer
{
bool isconnected = Blynk.connected();
if (isconnected == false)
{
MODE = 1;
digitalWrite(LED1, LOW);
}
if (isconnected == true)
{
MODE = 0;
digitalWrite(LED1, HIGH);
Blynk.syncAll();
}
}

void setup()
{
Serial.begin(115200);
Serial.println("n Starting");
pinMode(button, INPUT);
pinMode(switch_1, INPUT);
pinMode(relay_1, OUTPUT);

pinMode(switch_2, INPUT);
pinMode(relay_2, OUTPUT);
pinMode(switch_3, INPUT);
pinMode(relay_3, OUTPUT);

pinMode(switch_4, INPUT);
pinMode(relay_4, OUTPUT);

pinMode(LED1, OUTPUT);

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

digitalWrite(LED1, HIGH);
delay(200);
digitalWrite(LED1, LOW);
delay(200);
digitalWrite(LED1, HIGH);
delay(200);
digitalWrite(LED1, LOW);
delay(200);
digitalWrite(LED1, HIGH);
delay(200);
digitalWrite(LED1, HIGH);
delay(200);
digitalWrite(LED1, LOW);
delay(200);
digitalWrite(LED1, HIGH);
delay(200);
digitalWrite(LED1, LOW);
delay(200);
digitalWrite(LED1, HIGH);
delay(200);
digitalWrite(LED1, LOW);
delay(200);
WiFi.begin(ssid, pass);
timer.setInterval(3000L, Blynk_status); // check if connected to Blynk server every 3 seconds
Blynk.config(auth);
}

void loop()
{
if ( digitalRead(button) == LOW ) {
WiFiManager wifiManager;
if (!wifiManager.startConfigPortal("Home Automator","1234")) {
Serial.println("failed to connect and hit timeout");
delay(3000);
ESP.reset();
delay(3000);
}
Serial.println("connected...:)");
}
if (WiFi.status() == WL_CONNECTED)
{
Blynk.run();
}

timer.run(); // Initiates SimpleTimer
if (MODE == 0)
internet();
else
no_internet();
}
```
Please help me. I tried a lot to fix it but nothing happens. I checked the Com port in device manager and all the other necessary settings all were right here are the settings in Arduino ide.[![enter image description here][3]][3] Please help me Thanks in advance.

  [1]: https://i.stack.imgur.com/7wOZC.png
  [2]: https://i.stack.imgur.com/REW2M.png
  [3]: https://i.stack.imgur.com/ruchi.png

title: Wemos d1 mini code not uploading

Answers: 0


body:
Platform
- Attiny85 with AttinyCores
- 1306 OLED i2c with Tiny4KDisplay

Goal
- using a joystick for menu navigation
  - up/down choose
  - left enter (not finished yet)
  - right back (not finished yet)
  - inverse display the chosen item.

I come from python word which is why I am using a linked list for menu navigation. I found a weird bug that stops me from displaying some of the long text. I found that if the defined Nodes over a certain amount of number, item text over 5 chars will not display. I don't know why this is related to the number of instances. I managed to narrow down the range of the bug. In the code. if those 3 lines are commented, all the items are displayed correct, if not, only up to `ccccc` but not `dddddd`.

[![without the 3 lines, (commented)][1]][1]
[![with the 3 lines, (uncommented)][2]][2]

The flash and RAM consumption of the failure situation is
```
Sketch uses 5180 bytes (63%) of program storage space. Maximum is 8192 bytes.
Global variables use 280 bytes (54%) of dynamic memory, leaving 232 bytes for local variables. Maximum is 512 bytes.
```

My code is as below. I broke it into parts to highlighted the problem. But it is a continuous file actually.

Thank you for any insight.

PS: I know there are methods that avoid oop, but I think this weird bug is so close to being fixed, (or proved to be an actual bug in the package/compiler). So I would like to pursue an answer to this question.

Update:

I tried to use another method that uses a List of Strings instead of a class to achieve the same function. The Bug is still there. I guess it is because there are too many instances of String. The question is not changed: "Is there a limitation of how many instances of the `String` class?".

```c

#include <Tiny4kOLED.h>

// input setup
int x = 512;
int y = 512;
int lastx = 512;
int lasty = 512;

bool left = false;
bool right = false;
bool up = false;
bool down = false;

char input() {
  x = analogRead(A2);
  y = analogRead(A3);
  if( (lastx > 256) & (x <= 256) ){
    left = true;
  }
  if( (lastx < 768) & (x >= 768) ){
    right = true;
  }
  if( (lasty > 256) & (y <= 256) ){
    down = true;
  }
  if( (lasty < 768) & (y >= 768) ){
    up = true;
  }
  lastx = x;
  lasty = y;
}

// item data
class Node
{
  public:
    String text;
    uint8_t id;
    Node * next;
    Node * previous;
    Node * parent;
    Node * child;
    Node(String s, int n){
      text = s;
      id = n;
      next = NULL;
      previous = NULL;
      parent = NULL;
      child = NULL;
    }
    void append_next(Node * other){
      this->next = other;
      other->previous = this;
      other->parent = this->parent;
    }
    void append_child(Node * other){
      this->child = other;
      other->parent = this;
    }
};

Node main_0("aaa", 1);
Node main_1("bbbb", 2);
Node main_2("ccccc", 3);
Node main_3("dddddd", 4);
Node main_4("eeeeeee", 5);
Node main_5("ffffffff", 6);
```
# This is how the error can be repeated.
```c
/* Uncomment The following 3 lines will cause the problem*/
//Node item_0_0("aaa", 7);
//Node item_0_1("bbb", 8);
//Node item_0_2("ccc", 9);
```
```c
Node * current_sel = (&main_0);
Node * screen_top = (&main_0);

void setup() {
  // oled setup
  oled.begin(0,0);
  oled.enableChargePump();
  oled.setRotation(1);
  // oled.setInternalIref(true);
  oled.enableZoomIn();
  oled.setFont(FONT6X8);
  oled.clear();
  oled.switchRenderFrame();
  oled.clear();
  oled.switchFrame();
  oled.on();
  // oled setup end

  // input setup
  pinMode(A2, INPUT); // X
  pinMode(A3, INPUT); // Y
  // input setup end

  // data
  main_0.append_next(&main_1);
  main_1.append_next(&main_2);
  main_2.append_next(&main_3);
  main_3.append_next(&main_4);
  main_4.append_next(&main_5);
}

void loop() {
  // input read
  input();

  // move current;
  if(up){
    up = false;
    if(current_sel->previous != NULL){
      if(screen_top == current_sel){
        screen_top = screen_top->previous;
      }
      current_sel = current_sel->previous;
    }
  }

  if(down){
    down = false;
    if(current_sel->next != NULL){
      if(screen_top->next->next->next == current_sel){
        screen_top = screen_top->next;
      }
      current_sel = current_sel->next;
    }
  }

  // oled update
  oled.clear();

  oled.setCursor(64, 0);
  oled.print(current_sel->text);

  Node * current_draw = screen_top;
  int i = 0;
  while(true){

    oled.setCursor(0,i);
    if(current_draw == current_sel){
      oled.invertOutput(true);
    }
    oled.print(current_draw->text);
    oled.invertOutput(false);

    if(current_draw->next == NULL){
      break;
    }

    current_draw = current_draw->next;
    i++;
    if(i >= 4){
      break;
    }
  }

  oled.switchFrame();
  delay(50);
}
```

  [1]: https://i.stack.imgur.com/usqFz.jpg
  [2]: https://i.stack.imgur.com/Foab3.jpg

Answers: 2

body:
**Do not** use `String`. Ever. Especially not on a chip with such a tiny amount of RAM.

`String` uses dynamic allocation to store the string data in RAM. This is very inefficient, especially when you are working with string literals.

Those literals must be stored in flash, not RAM, so you need to be working with `const char *` and `PROGMEM`, along with the `F()` macro.

When using a chip with only a few hundred bytes of RAM you *need* to be as efficient as you possibly can. You *need* to account for each and every byte you use - and you just can't do that with `String`.

---

As an example, let's look at what this does:

```c++
Node main_5("ffffffff", 6);
```

You have a string of 8 characters plus a NULL terminating character. That's 9 bytes.  Those 9 bytes are copied into RAM at boot time. Current total 9 bytes. You then convert that to a `String` and copy the character data into that temporary object - that's now 18 bytes plus the size of the `String` object. Then:

```c++
text = s;
```
You allocate 9 bytes inside the `text` `String` object and copy the data in.  You're now at 27 bytes plus two `String` objects (one of which you created earlier in your class).  A little over 5% of your entire memory just to move text around the place.  A third of that you claw back from your heap as the objects leave scope, but then you have a hole in your heap. And this is the last set of operations after you've already made a complete mess of your heap with the earlier ones.

Whereas

```c++
const char main_5[] PROGMEM = "ffffffff";
```
uses just 2 bytes of RAM to store the pointer and nothing else.

body:
Each instance of your class uses RAM to store its data. There is *always* a limit to the number of instances; not a fixed number, but a limit imposed by the quantity of RAM available. What Majenko wrote about `String`s applies equally to class instances, if instances are constructed and destroyed during the run.

A fixed number of global instances, as you have used, is more efficient but there is still only room for so many. Complicating this is the fact that RAM is a shared resource. Static variables like globals, including global class-instances, are assigned from the bottom of RAM, upward, after all of the compilations are done and before uploading to the chip. The program's run-time stack, which includes each function's automatic local data, builds from the top of RAM, downward, during the run. Stack memory is assigned and released as each function is entered and exited. But when a function calls a function which calls a function, which calls ..., the stack has to keep growing until the final call returns and the previous calls may then return.

If you attempted to define a large number of instances with a small amount of RAM available, the IDE (actually the linker, which puts together all of your code and the libraries you use) would catch the problem before your program gets uploaded.

But in the case where there all of the RAM didn't get assigned at compile- or link-time, then at run time, your stack could still possibly grow downward until it collides with the global- and fixed-data at the bottom of RAM, with (unfortunately) unpredictable results, but definitely unexpected and improper operation.

Update:
I did gloss over some details, as two commenters were kind enough to point out. Yes, the heap - memory allocated dynamically at run-time - occupies the space just above the globals and other static memory allocations. Heap space can grow, the more it is used to allocate and de-allocate memory, and being low in memory, would have to grow upward, toward the stack. It is the heap where String data is allocated and re-allocated and is one of the reason's behind Majenko's warning against using the String type - especially if the strings will be edited at run time, which results in re-allocation that may not be obvious.

It is also worth noting that any class uses memory, whether Strings or user defined classes such as the OP's nodes. They are both classes and their instances will be handled similarly.

Also in OP's case, note that the class instances are allocated 'statically' - all instances are known and allocated during the run setup and not altered during the run. In 'quotes', because the allocation actually does happen during run-time, but at the very start of the run, and prior to the user sketch receiving control.


body:
Folks,

I use the RCSwitch sketch to notify my WiFi alarm controller when a motion is detected.

Using the Receiver Code, I have got the following information related to the motion detection signal from the PIR (detector):

```
Decimal: 8876073 (24Bit)
Binary: 100001110111000000101001
Tri-State: not applicable
PulseLength: 311 microseconds
Protocol: 1
Raw data: 9700,1096,264,400,952,420,964,380,968,372,1012,1040,316,1028,324,1016,380,332,1008,1012,340,1040,344,1000,348,356,1024,324,1016,332,1012,372,1016,336,1012,372,1008,1016,336,328,1016,1008,380,324,1016,368,1012,1008,344,
```

My Transmitter Sketch is as follows:

```
#include <RCSwitch.h>
RCSwitch mySwitch = RCSwitch();
void setup() {
 Serial.begin(9600);
 // Transmitter is connected to Arduino Pin #10
 mySwitch.enableTransmit(10);
 // Optional set pulse length.
 mySwitch.setPulseLength(312);
 // set protocol (default is 1, will work for most outlets)
 // mySwitch.setProtocol(2);
 // Optional set number of transmission repetitions.
 mySwitch.setRepeatTransmit(5);
 pinMode(13,OUTPUT);
}
void loop() {
 mySwitch.send("100001110111000000101001");//Detection Signal
 //mySwitch.send("100001110111000000101001");//Detection Signal
 //mySwitch.send("101110100000000011000010");//Panic Signal
 //mySwitch.send("101110100000000011000010");//Panic Signal
 Serial.print("Sent 100001110111000000101001 ");
 digitalWrite(13,HIGH);
 delay(500);
 digitalWrite(13,LOW);
 delay(10000);
}
```

While it appears the message is being sent, unfortunately my Alarm Control doesn't detect it.

Can anyone suggest a fix please?

Ranjith

title: RCSwitch for Alarm System

Answers: 0


body:
I have a webserver configured on my esp8266 with is set to fire off electrical relay0 on my 8 port relay board.
The device initializes relay0 perfectly and without errors.
But when I configure the second relay1, i get no response from my second url.

    //note, when you write to low, you turn the switchport on. It's backwards for some reason
    #include <ESP8266WiFi.h>
    #define statusLed 2   // built-in led for the ESP8266-12

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

    int switchPin0 = 16;
    int switchPin1 = 5;
    int switch0;
    int switch1;

    WiFiServer server(80);

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

      pinMode(statusLed, OUTPUT);
      pinMode(switchPin0, OUTPUT);
      digitalWrite(switchPin0, HIGH);

      // Connect to WiFi network
      Serial.println();
      Serial.println();
      Serial.print("Connecting to ");
      Serial.println(ssid);

      WiFi.begin(ssid, password);

      while (WiFi.status() != WL_CONNECTED) {
        delay(500);
        Serial.print(".");
      }
      digitalWrite(statusLed, HIGH);
      Serial.println("");
      Serial.println("WiFi connected");

      // Start the server
      server.begin();
      Serial.println("Server started");

      // Print the IP address
      Serial.print("Use this URL : ");
      Serial.print("http://");
      Serial.print(WiFi.localIP());
      Serial.println("/");

    }

    void loop() {
      // Check if a client has connected
      WiFiClient client = server.available();
      if (!client) {
        return;
      }

      // Wait until the client sends some data
      Serial.println("new client");
      while(!client.available()){
        delay(1);
      }

      // Read the first line of the request
      String request = client.readStringUntil('\r');
      Serial.println(request);

      client.flush();

      // Match the request

      int value = HIGH;
      if (request.indexOf("/SWITCH=0") != -1){
        digitalWrite(switchPin0, LOW);
        digitalWrite(statusLed, LOW);   // blink led
        delay(1);
        digitalWrite(statusLed, HIGH);
        //set water pump time here
        delay(8000);
        digitalWrite(switchPin0, HIGH);
        value = HIGH;
        ++switch0;
      } else if (request.indexOf("/SWITCH=1") != -1){
        digitalWrite(switchPin1, LOW);
        digitalWrite(statusLed, LOW);   // blink led
        delay(1);
        digitalWrite(statusLed, HIGH);
        //set water pump time here
        delay(8000);
        digitalWrite(switchPin1, HIGH);
        value = HIGH;
        ++switch1;
      } else {

        }

      // Return the response
      client.println("HTTP/1.1 200 OK");
      client.println("Content-Type: text/html");
      client.println(""); //  do not forget this one
      client.println("<!DOCTYPE HTML>");
      client.println("");

      client.print("Switch pin is now: ");

      if(value == HIGH) {
        client.print("Off");
      } else {
        client.print("On");
      }
      client.println("

");
      client.println("Switch 0");
      client.println("Click here  to send a measured amount
");
      client.println("Number of times plant 0 has been fed is ");
      client.println(switch0);
      client.println("

");
      client.println("Switch 1");
      client.println("Click here  to send a measured amount
");
      client.println("Number of times plant 1 has been fed is ");
      client.println(switch1);
      client.println("");

      delay(1);
      Serial.println("Client disconnected");
      Serial.println("");
      digitalWrite(statusLed, LOW);   // blink led
      delay(1);
      digitalWrite(statusLed, HIGH);

    }

my counter will update, but the relay pin never fires for relay1. relay0 works fine. I can swap the ports and then the second relay will work and not the first. I just can't manage both.

How do I get a second (or more) relay ports to initialize via webpage?

title: How do I make two (or more) pins available on my server url?

Answers: 1

body:
It looks like you forgot to initialize `switchPin1` to be an output.

Add the following to your `setup()` (for example, right after the corresponding initialization commands for `switchPin0`):

    void setup() {
        ....
        pinMode(switchPin1, OUTPUT);
        digitalWrite(switchPin1, HIGH);
        ....
    }


body:
I pieced together a sketch to control a servo that turns an encoder. Eventually I plan to build this up to a DMX input, so I have the input range from 0 - 255.
Basically, it's supposed to ask you to input range from 0 to 255 and then it changes that value to 0 -180 for servo control. Then it's supposed to compare that to the encoder and rotate the correct direction until the encoder value and requested values match. I'm just learning arduino so I'm sure I've made some mistake. Here is the code:

```c++
// Rotary Encoder Inputs
#define inputCLK 22
#define inputDT 24

#include <Servo.h>

Servo myservo;
int pos = 90;
int counter = 90;
int currentStateCLK;
// Setup Serial Monitor

// Read the initial state of inputCLK
// Assign to previousStateCLK variable
int previousStateCLK;

String encdir ="";

void setup() {
  Serial.begin (9600);
  previousStateCLK = digitalRead(inputCLK);
  // Set encoder pins as inputs
  pinMode (inputCLK,INPUT);
  pinMode (inputDT,INPUT);
  myservo.attach(9);

void loop() {
  Serial.println("Enter a number from 0 to 255");
  while (Serial.available() == 0); {}
  int val = Serial.parseInt(); // read int or parseFloat for ..float...
  long Pos = val;
  Pos = Pos * 180 / 255;
  Serial.println(val);
  Serial.println(Pos);
  if (Pos > Counter) {
    myservo.write 0;
  }
  if (Pos < Counter) {
    myservo.write 180;
  }
  if (Pos = Counter) {
    myservo.write 90;
  }

  // Read the current state of inputCLK
  currentStateCLK = digitalRead(inputCLK);

  // If the previous and the current state of the inputCLK are different then a pulse has occured
  if (currentStateCLK != previousStateCLK) {
    // If the inputDT state is different than the inputCLK state then
    // the encoder is rotating counterclockwise
    if (digitalRead(inputDT) != currentStateCLK) {
      counter --;
      encdir ="CCW";
    } else {
      // Encoder is rotating clockwise
      counter ++;
      encdir ="CW";
    }
    Serial.print("Direction: ");
    Serial.print(encdir);
    Serial.print(" -- Value: ");
    Serial.println(counter);
  }
  // Update previousStateCLK with the current state
  previousStateCLK = currentStateCLK;
}
```
So when I run the program, I'm not getting any movement on the servo.

Thanks.

title: Using a Encoder Feedback to control a 360 degree servo

Answers: 1

body:
Your initial problem is here:

```c++
  if (Pos = Counter) {
```

If the result (fall through) of assigning Counter to Pos is non-zero then stop.

That's not right.  You're assigning, not comparing. In C `==` is comparison and `=` is assignment.  Instead it should read:

```c++
  if (Pos == Counter) {
```

However there is another, more sneaky, problem with your code - the usage of `Serial.parseInt()`.

If you send the string `56\r\n` as you typically would (with the CR+LF line ending typical of serial communication) then `parseInt` will read the first portion of the string up to and including the first non-digit character and parse it as a number. That is, the `56\r` and return the value 56.  Then on the next pass it will see there is still data in the serial buffer and parse it, up to and including the first non-digit character - which is just `\n`. So it will return 0.

That means the first pass through `loop()` you get 56, and then immediately after in the next pass through `loop()` you get 0.

And then, looking at your code a third time, there is another bigger problem: you block waiting for serial input, and your `Pos` variable is local and will be lost each iteration. I think you meant to use `pos`, which is a global variable, and not create a new `long Pos` variable each iteration. And where is `Counter` defined? That surely should be the global `counter` variable?

If you're blocking waiting for serial input then how can you be controlling the servo to get it to the desired location?

So, in short, there are so many errors and problems with your code that you need to go back to basics and re-think / re-write many portions of it.


body:
I'm very new to arduino and have to work on a project for school. We have connected 3 motors (Servo, Stepper (180 degrees) and a DC motor) to an Arduino Uno, Adafruit motorshield and a pcb. With the pcb we were able to record values of the motors individually and use these values to create a playback motion. The code which we got for the playback motion is below (I've already filled in my values for the 3 motors).

This is what I want to do with the motors:

When I press a button I want to 'start' the cycle of motor motions
1) first the dc motor starts doing the motion based on the chosen values
2) When this stops after 5 seconds I want the servo motor to do it's motion
3) When the servo motor is done, I want the stepper motor to start doing the motion based on the chosen values for 5 seconds and then stop.

We were told not to use a delay and someone suggested to use millis() instead of delay() but since I am a beginner I have no idea where to start.

This is the code:

```
// With this code it is possible to play back recorded motion paths for for motors connected to the Adafruit motorshield

#include <AccelStepper.h>
#include <Wire.h>
#include <Adafruit_MotorShield.h>
#include <Servo.h> // this is a library that allows you to drive servo's.

// variables
int modeChoice = 0;

int buttons = A2;  // the three buttons share an analog pin, resitors provide different levels that point to which button is pressed
int slide = A1;    // the slide is read through one analog pin, resitors provide different levels that point to which slide position is current
int rotation = A0; // the pin for the potentiometer

int buttonPressed = 0; // a variable to remember which button is pressed, it is used to control leds and motion memory position management

int buttonValRaw = 0; // a variable to store the raw analog reading of the buttons pin
int slideValRaw = 0;  // a variable to sore the raw analog reading of the slide pin
int valButton = 0;    // a variable to store the interpreted value, the exact pointer to a button
int valSlide = 0;     // a variable to store the interpreted value, the exact pointer to a slide position
int idleState = 0;    // a variable to toggle the servo idle behavior
int resetMotion = 0;  // a variable to return the arrayPosition to 0 if a button is pushed so that the behaviour starts at the beginning
int motionVar1;       // a variable to hold a motion position
int motionVar2;       // another variable to hold a motion position

int mySensorArray[20];  // an array with 20 slots to store raw potentiometer readings (for filtering)
int sensorArrayPos = 0; // the array position of interest.

//////////////////////////////////////

int servoMotionArray_B1[50] = {95, 95, 95, 95, 65, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; // paste your 50 values in between the brackets

int DCMotionArray_B1[50] = {-85, -85, -85, -85, -85, -85, -85, -85, -85, -85, -85, -85, -85, -85, -85, -85, -85, -85, -85, -85, -85, -85, -85, -85, -85, -85, -85, -85, -85, -85, -85, -85, -85, -85, -85, -85, -85, -85, -85, -85, -85, -85, -85, -85, -85, -85, -85, -85, -85, -85};

//recorded motions for position implementation
int StepperMotionArray_B1[50] = {-200,-200,-200,-200,-200,-200,-200,-200,-200,-200,-200,-200,-200,-200,-200,-200,-200,-200,-200,-200,-200,-200,-200,-200,-200,-200,-200,-200,-200,-200,-200,-200,-200,-200,-200,-200,-200,-200,-200,-200,-200,-200,-200,-200,-200,-200,-200,-200,-200,-200};

//////////////////////////////////////

int arrayPosition = 0;

unsigned long mainTimer = 0; // a variable to time recording and playback
int timeBetweenSamples = 100; // the time between samples.

unsigned long debounceTimer = 0; // a variable to control a timer interval for debouncing of the buttons
int lastValButton = 0; // a variable to help debouncing of the buttons
int debounceFlag = 0; // another variabel to help debouncing of the buttons

// Setup motors
// Create the motor shield object with the default I2C address
Adafruit_MotorShield AFMS = Adafruit_MotorShield();
// Connect a stepper motor with 16 steps per revolution (2048 positions) to motor port #1 (M1 and M2) -- you need to change this if your stepper is on port #2
Adafruit_StepperMotor *myStepper = AFMS.getStepper(16, 1);
// And connect a DC motor to port M3 -- you need to change this if your DC is on a different port
Adafruit_DCMotor *myMotor = AFMS.getMotor(3);

Servo myservo1;   // servo object (employs the servo library that was included above)

// these are dedicated functions to make the steppermotor move
void forwardstep1() {
  myStepper->onestep(FORWARD, SINGLE);
}
void backwardstep1() {
  myStepper->onestep(BACKWARD, SINGLE);
}

//create aStepper object
AccelStepper aStepper(forwardstep1, backwardstep1); // use functions to step

// setup
void setup() {
  Serial.begin(9600); // start serial communication with 9600 baud rate

  AFMS.begin();  // create with the default frequency 1.6KHz
  //AFMS.begin(1000);  // OR with a different frequency, say 1KHz

  myservo1.attach(9); // attach servo object to pin 9

  // turn on motor M3
  myMotor->setSpeed(0);
  myMotor->run(RELEASE);

  // setup the stepper
  aStepper.setSpeed(0); // this is used in the 'speed' implementation

  aStepper.setMaxSpeed(200.0); // these are used in the 'position' implementation
  aStepper.setAcceleration(100.0);
  aStepper.moveTo(0);

  // synchronize the first timer cycle -- because the timer is starting at zero it generates negative values in the first 100 miliseconds after starting up when going through the timer cycle, creating potential erratic bahaviour-- giving it a delay at the end of the setup loop will eradicate this behaviour
  delay(1000);
}

void doButtons() {
  if (buttonPressed != 0) {
    return;
  }
  else {
    buttonValRaw = analogRead(buttons);
    valButton = map (buttonValRaw, 49, 605, 0, 5);
    int localButtonVal = valButton;

    if (valButton > 7) {
      return;
    }

    if (debounceFlag == 0) {
      debounceTimer = millis();
      debounceFlag = 1;
    }

    if (debounceTimer < millis() - 20) {

      buttonValRaw = analogRead(buttons);
      valButton = map (buttonValRaw, 49, 605, 0, 5);

      if (valButton == localButtonVal) {
        debounceFlag = 0;

        switch (valButton) {
          case 1:
            buttonPressed = 1;
            break;
          case 2:
            buttonPressed = 2;
            break;
          case 3:
            buttonPressed = 3;
            break;
          default:
            buttonPressed = 0;
            break;
        }
      }
    }
  }
}

void loop() {
  doButtons(); // this uses the buttons from the PCB, if you use your own implementation you need to reprogram this function

  if (mainTimer < millis() - timeBetweenSamples) { // sampling only once per interval.
    mainTimer = millis(); // time is rewritten to current millis starting a new interval.

    if (buttonPressed == 0) { //'idle play'
      if (idleState == 0) {
        motionVar1 = servoMotionArray_B1[arrayPosition];
      }
      else if (idleState == 1){
        motionVar1 = servoMotionArray_B1[arrayPosition];
      }
      motionVar2 = DCMotionArray_B1[arrayPosition];
      myservo1.write(motionVar1);
      if (motionVar2 < 0) {
        myMotor->run(BACKWARD);
        myMotor->setSpeed(abs(motionVar2));
      }
      else if (motionVar2 >= 0) {
        myMotor->run(FORWARD);
        myMotor->setSpeed(motionVar2);
      }
      arrayPosition++;
      if (arrayPosition > 49) {
        arrayPosition = 0;
        idleState = !idleState;
      }
    }

    if (buttonPressed == 1) { //2nd behaviour
      if (resetMotion == 0) {
        arrayPosition = 0;
        resetMotion = 1;
        myMotor->run(RELEASE); // release the DC motor, otherwise it will continue spinning at the last known RPM
      }
      motionVar1 = servoMotionArray_B3[arrayPosition];
      motionVar2 = StepperMotionArray_B1[arrayPosition];
      myservo1.write(motionVar1);
      aStepper.moveTo(motionVar2);
      arrayPosition++;
      if (arrayPosition > 49) {
        arrayPosition = 0;
        buttonPressed = 0;
        resetMotion = 0;
      }
    }
  }

  // one of these needs to be called to make the stepper motor work, comment out the one you do not need (position or speed)
  //aStepper.run(); //stepper position implementation
  aStepper.runSpeed(); //stepper speed implementation

}
```

title: How to make motors start when pressing a button, and then go through a cycle with a specific motor order?

Answers: 1

body:
You're almost correct already:

    if (millis() - mainTimer >= timeBetweenSamples) {
      mainTimer = millis();
      // executing only once per interval.

      ... the action for current arrayPosition ...

      arrayPosition++;
      if (arrayPosition > 49) {
         arrayPosition = 0;
         buttonPressed = 0; // Show ends
      }
    }


body:
Perhaps I'm not fully understanding a difference between logic level and the function of the TX and RX pins? I'm just wondering if an ESP can send, one-way, data to an Arduino. (I found that two-way communication would need a logic level converter.)

ESP32 Datasheet
[![enter image description here][1]][1]
https://www.espressif.com/sites/default/files/documentation/esp32_datasheet_en.pdf#page=42

---

Arduino datasheets do not appear to specify logic level tolerances. It appears from [this Arduino Forum post][2], it would work.

Is it universally assumed that 3v3 will be in tolerance for logic high?
[![enter image description here][3]][3]
https://learn.sparkfun.com/tutorials/logic-levels/all

  [1]: https://i.stack.imgur.com/rO9Xs.png
  [2]: https://forum.arduino.cc/index.php?topic=386191.0
  [3]: https://i.stack.imgur.com/7Y3iU.png

title: 3v3 ESP one way communication with 5 V Arduino?

Answers: 1

body:
Yes, it will work, but only just. It's borderline.

The ESP32 gives out at most 3.3V as a HIGH signal. The Arduino accepts "above 0.6Vcc" as a HIGH signal. That means that it needs to see a voltage that is at least 60% of the voltage on the Vcc pin (5V pin) of the Arduino.

If the Arduino has exactly 5V then 60% of that is 3V. Since 3.3V is higher than 3V it sees it has a HIGH.

However if the Arduino is being powered by a slightly higher voltage than 5V (some USB ports can give out 5.2V and it's still in spec) and if the ESP32 is being powered slightly below 3.3V, then that 0.3v margin of error gets narrower and narrower. Eventually it disappears and HIGH can no longer be detected.

For example if the Arduino has 5.2V and the ESP32 has 3.1V then the Arduino expects at least 3.12V and the ESP32 gives out no more than 3.1V.

So in  most circumstances it does work, but there are factors that can stop it from working. Those factors can be mitigated by using logic level translation.


body:
I am trying to use 3 TOF10120 Laser Sensors with one Arduino that all have the same, fixed I2C Address. I don't believe it is possible to change the I2C address of the TOF10120, but if I am wrong, please let me know (also, I need 3 different addresses). This being said, I am trying to use the SoftWire Library (https://github.com/stevemarple/SoftWire - very interesting library, but not great documentation) to help me to use my three sensors with Digital Pins. Does anyone have any experience with the SoftWire Library and how to get readings from a laser sensor?

I can provide the code I have, but it probably wouldn't be very helpful anyway. I am particularly curious as to how to use the DigitalWrite() and DigitalRead() functions for I2C with SoftWire.

Thanks for all the help in advance!

title: SoftWire Library Programming Questions for I2C with Digital Pins

Answers: 1

body: You can change the tof10120 to any i2c address between 1 and 254. you need to write the serial string 's7-xxx#' where xxx is the decimal address required (in string form). I wrote a simple python program for the raspberry pi to change my sensor addresses via the Rx Tx.


body:
I'm trying to modify Ben Eater's eeprom programmer to flash a 32K eeprom, since the arduino has 32K of program data total the data wouldn't fit in the program. So I wrote a python program using pySerial to send the data in chunks of 256 bytes over serial. The arduino program works correctly when I manually send the data over the serial monitor, and the python program works correctly when I print the values to a console as a test, but when I actually run the program over serial it seems to only write zeros to the eeprom. Additionally, the Rx led on the arduino seems to be lighting up with the correct data, but like I said only zeros are written.

Here's the relevant arduino code:
```
void setup() {
  pinMode(SHIFT_DATA, OUTPUT);
  pinMode(SHIFT_CLK, OUTPUT);
  pinMode(SHIFT_LATCH, OUTPUT);
  digitalWrite(WRITE_EN, HIGH);
  pinMode(WRITE_EN, OUTPUT);

  Serial.begin(57600);
  dataArrPage = 0;

  //delay(1000);
  //Serial.println("Reading EEPROM");
  //printContents();

}

void loop() {
  if (Serial.available() > 0) {
    int len = Serial.readBytes(dataArr, 256);

    for (int i = 0; i < 256; i++) {
      writeEEPROM(dataArrPage + i, dataArr[i]); // writeEEPROM(address, data)
    }
    dataArrPage += 0x100;

    Serial.write('s'); //success, writing is done
  }
}
```
And the relevant python code:
```
import time
import serial
ser = serial.Serial('/dev/ttyUSB0', 57600)
time.sleep(4) # wait for arduino to initialize

filename = input("Enter file name: ")
f = open(filename, "rb")
data = f.read()

page = 0
for x in range(128): # 128 pages in 32K eeprom
    for i in range(256):
        #print(hex(data[(page * 256) + i])) # printing prints the correct values
        ser.write(data[(page * 256) + i])
    page += 1

    #wait until receive 's' from arduino
    while True:
        if ser.in_waiting > 0:
            suc = ser.read(size=1)
            if suc == b's':
                print("Success")
                break

print("Writing done")
f.close()
ser.close()
```
I'm a beginner so sorry if it's something obvious.

title: EEPROM programmer works with serial monitor but not with pySerial

Answers: 1

body:
I figured out the problem. The for loop was writing one byte at a time, which probably wasn't fast enough and caused a timeout in the arudino. The code is now:
```
page = 0
for x in range(128): # 128 pages in 32K eeprom
    datalst = []
    for i in range(256):
        datalst.append(data[(page * 256) + i])

    ser.write(datalst)

    #wait until receive 's' from arduino
    while True:
        if ser.in_waiting > 0:
            suc = ser.read(size=1)
            if suc == b's':
                print("Success")
                break

    page += 1
```
I also changed the data types in the arduino sketch to use the ones in stdint.h which solved an unrelated bug. Let me know if I should post the full code for both.