Id
stringlengths
1
5
Tags
stringlengths
3
75
Title
stringlengths
15
150
CreationDate
stringlengths
23
23
Body
stringlengths
51
27.6k
Answer
stringlengths
42
31k
93641
|pwm|arduino-nano-every|
16 bit PWM on Nano Every
2023-07-01T16:24:53.187
<p>I need to drive a LED strip via MOSFET module. The module needs a high resolution PWM for very dim conditions. How can I set my pin to a 16 bit PWM resolution on an Arduino Nano Every?</p>
<p>Thanks again for your help KIIV. I can confirm it works. This an example of a low light PWM for an LED on Pin 10. Maybe it helps others.</p> <pre><code>int brightness = 0; // how bright the LED is int fadeAmount = 1; // how many points to fade the LED by void setup() { TCA0.SINGLE.PER = 0x4000; TCA0.SINGLE.CTRLA = TCA_SINGLE_CLKSEL_DIV16_gc | 1 &lt;&lt; TCA_SINGLE_ENABLE_bp TCA0.SINGLE.CMP1 = 65530; // initial value pinMode(10, OUTPUT); TCA0.SINGLE.CTRLB |= TCA_SINGLE_CMP1EN_bm; } void loop() { // set the brightness of LED pin: TCA0.SINGLE.CMP1 = brightness; // change the brightness for next time through the loop: brightness = brightness + fadeAmount; // reverse the direction of the fading at the ends of the fade: if (brightness &lt;= 0 || brightness &gt;= 64) { fadeAmount = -fadeAmount; } // wait to see the dimming effect delay(50); } </code></pre>
93650
|interrupt|isr|
Using interrupts as flags/latches without any ISR
2023-07-02T06:23:03.867
<p>I've got an Arduino Mega periodically running an (~400ms) operation that is sensitive to repeatable timing, so I don't ever want it to be interrupted. But, I'd like to be able to use an interrupt flag from one of the built-in peripherals (PCINT, comparator, etc.) to check afterward if an external event (say, a pin going high momentarily) ever happened during the operation.</p> <p>That is, it'd be nice if I could just treat one of the interrupt flags as a kind of async hardware latch that I can check (and reset) at my next earliest convenience instead of having my code interrupted.</p> <p>It wouldn't be hard to add a discrete latch IC, but I was hoping I could get away with just using what was already built into the AVR without adding more hardware (and using an extra pin to reset the latch).</p> <p>Looking at the documentation for each of the peripherals, it was unclear whether the flags will still be set when the interrupts themselves are disabled. I saw a mention someplace of an &quot;EMPTY_INTERRUPT&quot; macro, but I'm guessing that still generates an interrupt vector with a single &quot;return&quot; instruction, so I'd still be losing cycles to the interrupt preamble, etc.</p> <p>Can this be done without any ISR being called at all? Or do I need to add more hardware? I'm not sure wrapping the long-running task in noInterrupts()/interrupts() is a choice unless that also doesn't interfere with UART receiving. Thanks!</p>
<blockquote> <p>I'm not sure wrapping the long-running task in noInterrupts()/interrupts() is a choice ...</p> </blockquote> <p>That's right. Turning off interrupts would stop the timing/delay working so you wouldn't be able to time your 200 µs (unless you use delayMicroseconds).</p> <blockquote> <p>Each exposure is only a couple hundred microseconds, so even 2.625µs of periodic jitter would increase the exposure time by at least 1%.</p> </blockquote> <p>I think you might be better off using a hardware timer to time the exposure, rather than a loop. I generated VGA signals <a href="https://gammon.com.au/forum/?id=11608" rel="nofollow noreferrer">in a post here</a> where I wanted the horizontal and vertical sync to have no jitter whatsoever. The timers can be set to turn on, or off, an output pin, so that could be used to control your shutter. Then it would be completely precise.</p> <blockquote> <p>I didn't know the UART interrupts the CPU ...</p> </blockquote> <p>Incoming (or indeed outgoing) serial communications causes interrupts. The timers cause interrupts. In particular, if you haven't disabled it, Timer 0 generates interrupts which are counted so that millis() and micros() can function. You can disable interrupts but then timing exact intervals becomes problematic. My suggestion of using the timer hardware will give the most reliable and repeatable performance, in the same way that my VGA signal generation was completely without jitter.</p> <p>Because of the timer interrupts, if you haven't disabled interrupts, some of your exposures may have the timer interrupt in the middle (making them longer) and some not, or at least, a different number of interrupts. This will make the exposure time non-precise.</p> <hr /> <p>Another approach would be to turn off interrupts for the exposure only (ie. your 200 µs, not the 400 ms you mention), and then use delayMicroseconds() to time the exposure. Then when interrupts are back on the closure of a switch (an external interrupt) could be processed by a normal ISR. This might add slight differences to the time <em>between</em> exposures, but the exposure time itself would be constant.</p> <p>Even with interrupts off, an external interrupt is &quot;remembered&quot; and would be processed when interrupts are enabled again.</p> <hr /> <p>This is turning into <a href="https://en.wikipedia.org/wiki/XY_problem" rel="nofollow noreferrer">an XY problem</a> somewhat. It would have been better to mention your exact requirements (the photography part) rather than launching into questions about using interrupts as latches.</p> <hr /> <h1>Example code</h1> <p>To demonstrate how you can do this with timers, I have written some sample code:</p> <pre class="lang-cpp prettyprint-override"><code>// Example of strobing a flash FRAMES_TO_TAKE times to take pictures // The time between each flash is in TIME_BETWEEN_SEQUENCES // The flash &quot;on&quot; time is in STROBE_ON_TIME // // For Atmega328P (Arduino Uno and similar) // and Atmega2560 (Arduino Mega) // Author: Nick Gammon // Date: 4 July 2023 const byte FRAMES_TO_TAKE = 12; const byte CPU_CLOCK_SPEED = 16; // MHz const unsigned long TIME_BETWEEN_SEQUENCES = 20000; // µs const unsigned long STROBE_ON_TIME = 200; // µs const byte PRESCALER = 64; // set correct output pin #if defined(__AVR_ATmega168__) || defined(__AVR_ATmega328P__) const byte FLASH_PIN = 10; // OC1B (Output Compare Timer 1: B side) - Atmega328P #elif defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__) const byte FLASH_PIN = 12; // OC1B (Output Compare Timer 1: B side) - Atmeg12560 #else #error Processor not supported #endif volatile byte count; // how many times it fired // Timer 1 Compare &quot;B&quot; ISR vector // count up to the required number of exposures, then stop ISR (TIMER1_COMPB_vect) { if (++count &gt; FRAMES_TO_TAKE) { // stop timer 1 TCCR1A = 0; TCCR1B = 0; } // end if number of frames reached } // end of TIMER1_COMPB_vect // does one sequence of FRAMES_TO_TAKE shots and then stops void startSequence () { // stop timer 1 TCCR1A = 0; TCCR1B = 0; TCCR1A = bit (WGM10) | bit (WGM11); // fast PWM - top at OCR1A TCCR1B = bit (WGM12) | bit (WGM13); // (mode 15) TCCR1A |= bit (COM1B1); // Set OC1B during duty cycle OCR1A = ((TIME_BETWEEN_SEQUENCES * CPU_CLOCK_SPEED) / PRESCALER) - 1; // total cycle time OCR1B = ((STROBE_ON_TIME * CPU_CLOCK_SPEED) / PRESCALER) - 1; // duty cycle time count = 0; TCNT1 = 0; // reset timer count TIFR1 = bit (OCF1B); // clear &quot;compare B&quot; flag TIMSK1 = bit (OCIE1B); // interrupt on compare B match TCCR1B |= bit (CS10) | bit (CS11); // start timer with prescaler of 64 } // end of startSequence void setup () { // stop timer 1 TCCR1A = 0; TCCR1B = 0; // set up pin so we can toggle it pinMode (FLASH_PIN, OUTPUT); digitalWrite (FLASH_PIN, LOW); // for debugging etc. Serial.begin (115200); } // end of setup void loop () { startSequence (); delay (20); Serial.print (&quot;But does it get goat's blood out?\n&quot;); delay (1000); } // end of loop; </code></pre> <hr /> <h1>Code explanation</h1> <p>What this code does is use Timer 1 to time the intervals you require. Based on what you posted earlier, I have assumed:</p> <ul> <li>12 exposures in a &quot;session&quot; (FRAMES_TO_TAKE) - you said &quot;a dozen or so&quot;</li> <li>Exposures are to be 20 ms apart (TIME_BETWEEN_SEQUENCES) - so a session is 240 ms</li> <li>Exposure time is to be 200 µs (STROBE_ON_TIME) - you said &quot;a couple of hundred microseconds&quot;</li> <li>You want to do other stuff like serial comms, checking switches etc.</li> </ul> <p>The function <code>startSequence</code> initiates the timer which has a period of 20 ms and a duty cycle of 200 µs. At the completion of a duty cycle the ISR is called which counts duty cycles. At the end of the nominated number (12) the timer is turned off.</p> <p>The output pin (pin 12 on the Mega, pin 10 on the Uno) is turned on during the duty cycle (ie. for 200 µs and off the rest of the time). Because this is done in hardware there is no jitter at all. In my demo I am doing serial comms to show that the intervals are exactly correct, despite the interrupts caused by the comms.</p> <hr /> <h1>Logic analyser output</h1> <p>The logic analyser screenshot shows that the intervals are exactly correct (to within a fraction of a percent). In any case the intervals are consistent with each other.</p> <p><a href="https://i.stack.imgur.com/inRFb.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/inRFb.png" alt="Logic analyser output" /></a></p> <p>This second screenshot shows that there are 12 pulses in that interval.</p> <p><a href="https://i.stack.imgur.com/Fh9DJ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Fh9DJ.png" alt="Logic analyser showing count of pulses" /></a></p> <p>I have used a prescaler of 64 to get a nice long interval that can be timed (without overflowing the 16-bit counter size). This gives a granularity of 64 clock cycles (4 µs).</p> <hr /> <h1>Timer 1 cheat sheet</h1> <hr /> <p><a href="https://i.stack.imgur.com/yPLpA.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/yPLpA.png" alt="Timer 1 cheat sheet" /></a></p>
93657
|i2c|
I2C cabling rules for 2+ devices
2023-07-02T22:39:57.583
<p>I'm attempting to wire two breakout boards with i2c devices to a Mega2560:</p> <ul> <li>a HD44280 LCD with PCF8574 i2c backpack</li> <li>a combo board with DS1307 + AT24C32</li> </ul> <p>There are two obvious possibilities for cabling:</p> <ul> <li><p>two 10-inch ribbon cables that come together right before connecting to the Arduino's SDA and SCL pins. Technically, one could be 6 inches... but I know that with RS485, you're asking for trouble if you do a star with branches of unequal length. The cables can't really be any shorter without seriously impairing my ability to debug it while partially disassembled (the LCD is mounted to the lid, and the cables are long enough to allow me to lay the lid on the desk next to the enclosure and power everything up without putting stress on the cables).</p> </li> <li><p>Same 10-inch segments of ribbon cable, but daisy-chained... Arduino to LCD, LCD to RTC. In this case, the second one really needs to be 10&quot;, because it's mounted to the only clear spot inside the case I have.</p> </li> </ul> <p>Is one likely to be better or worse than the other?</p> <p>Are there any rules about WHERE the pullup resistors have to go? The DS1307 module has built-in pullup resistors. Do I have to somehow disable them &amp; use resistors right at the point where the bus connects to the Arduino's SDA &amp; SCL pins, or can the pullups go pretty much anywhere on the bus (including at one end of a star, or at the far end of a daisy chain)?</p>
<p>I2C is generally slow. You don't have to worry about how to route the device connection. Because propagation delay won't be a matter. The main goal should be to minimize the capacitance of the wiring, which means minimizing the total wire length. But as you mentioned one of the cable lengths is fixed, then keep the other one to a minimum. The star topology will work if you keep the wire lengths within 10 inches.</p>
93663
|serial|
Why is the serial monitor not printing a variable?
2023-07-03T14:45:25.820
<p>I connected an Adafruit color sensor to my Arduino and am having it make calculations. However, when the calculations are done and sent to the serial monitor, it says &quot;NDVI: &quot; without printing the value. The code is attached below. Thanks!</p> <p>Code:</p> <pre><code>/* TSL2591 Digital Light Sensor */ /* Dynamic Range: 600M:1 */ /* Maximum Lux: 88K */ #include &lt;Wire.h&gt; #include &lt;Adafruit_Sensor.h&gt; #include &quot;Adafruit_TSL2591.h&quot; #define IR850 5 #define IR940 6 #define BLUE 9 #define GREEN 10 #define RED 11 // Example for demonstrating the TSL2591 library - public domain! // connect SCL to I2C Clock // connect SDA to I2C Data // connect Vin to 3.3-5V DC // connect GROUND to common ground Adafruit_TSL2591 tsl = Adafruit_TSL2591(2591); // pass in a number for the sensor identifier (for your use later) /**************************************************************************/ /* Displays some basic information on this sensor from the unified sensor API sensor_t type (see Adafruit_Sensor for more information) */ /**************************************************************************/ void displaySensorDetails(void) { sensor_t sensor; tsl.getSensor(&amp;sensor); Serial.println(F(&quot;------------------------------------&quot;)); Serial.print (F(&quot;Sensor: &quot;)); Serial.println(sensor.name); Serial.print (F(&quot;Driver Ver: &quot;)); Serial.println(sensor.version); Serial.print (F(&quot;Unique ID: &quot;)); Serial.println(sensor.sensor_id); Serial.print (F(&quot;Max Value: &quot;)); Serial.print(sensor.max_value); Serial.println(F(&quot; lux&quot;)); Serial.print (F(&quot;Min Value: &quot;)); Serial.print(sensor.min_value); Serial.println(F(&quot; lux&quot;)); Serial.print (F(&quot;Resolution: &quot;)); Serial.print(sensor.resolution, 4); Serial.println(F(&quot; lux&quot;)); Serial.println(F(&quot;------------------------------------&quot;)); Serial.println(F(&quot;&quot;)); delay(500); } /**************************************************************************/ /* Configures the gain and integration time for the TSL2591 */ /**************************************************************************/ void configureSensor(void) { // You can change the gain on the fly, to adapt to brighter/dimmer light situations //tsl.setGain(TSL2591_GAIN_LOW); // 1x gain (bright light) //tsl.setGain(TSL2591_GAIN_MED); // 25x gain tsl.setGain(TSL2591_GAIN_HIGH); // 428x gain // Changing the integration time gives you a longer time over which to sense light // longer timelines are slower, but are good in very low light situtations! //tsl.setTiming(TSL2591_INTEGRATIONTIME_100MS); // shortest integration time (bright light) // tsl.setTiming(TSL2591_INTEGRATIONTIME_200MS); // tsl.setTiming(TSL2591_INTEGRATIONTIME_300MS); // tsl.setTiming(TSL2591_INTEGRATIONTIME_400MS); // tsl.setTiming(TSL2591_INTEGRATIONTIME_500MS); tsl.setTiming(TSL2591_INTEGRATIONTIME_600MS); // longest integration time (dim light) /* Display the gain and integration time for reference sake */ Serial.println(F(&quot;------------------------------------&quot;)); Serial.print (F(&quot;Gain: &quot;)); tsl2591Gain_t gain = tsl.getGain(); switch(gain) { case TSL2591_GAIN_LOW: Serial.println(F(&quot;1x (Low)&quot;)); break; case TSL2591_GAIN_MED: Serial.println(F(&quot;25x (Medium)&quot;)); break; case TSL2591_GAIN_HIGH: Serial.println(F(&quot;428x (High)&quot;)); break; case TSL2591_GAIN_MAX: Serial.println(F(&quot;9876x (Max)&quot;)); break; } Serial.print (F(&quot;Timing: &quot;)); Serial.print((tsl.getTiming() + 1) * 100, DEC); Serial.println(F(&quot; ms&quot;)); Serial.println(F(&quot;------------------------------------&quot;)); Serial.println(F(&quot;&quot;)); } /**************************************************************************/ /* Program entry point for the Arduino sketch */ /**************************************************************************/ void setup(void) { pinMode(IR850, OUTPUT); pinMode(IR940, OUTPUT); pinMode(RED, OUTPUT); pinMode(GREEN, OUTPUT); pinMode(BLUE, OUTPUT); digitalWrite(IR850, LOW); digitalWrite(IR940, LOW); digitalWrite(RED, LOW); digitalWrite(GREEN, LOW); digitalWrite(BLUE, LOW); Serial.begin(9600); Serial.println(F(&quot;Starting Adafruit TSL2591 Test!&quot;)); if (tsl.begin()) { Serial.println(F(&quot;Found a TSL2591 sensor&quot;)); } else { Serial.println(F(&quot;No sensor found ... check your wiring?&quot;)); while (1); } /* Display some basic information on this sensor */ displaySensorDetails(); /* Configure the sensor */ configureSensor(); // Now we're ready to get readings ... move on to loop()! } /**************************************************************************/ /* Shows how to perform a basic read on visible, full spectrum or infrared light (returns raw 16-bit ADC values) */ /**************************************************************************/ void simpleRead(void) { // Simple data read example. Just read the infrared, fullspecrtrum diode // or 'visible' (difference between the two) channels. // This can take 100-600 milliseconds! Uncomment whichever of the following you want to read uint16_t x = tsl.getLuminosity(TSL2591_VISIBLE); //uint16_t x = tsl.getLuminosity(TSL2591_FULLSPECTRUM); //uint16_t x = tsl.getLuminosity(TSL2591_INFRARED); Serial.print(F(&quot;[ &quot;)); Serial.print(millis()); Serial.print(F(&quot; ms ] &quot;)); Serial.print(F(&quot;Luminosity: &quot;)); Serial.println(x, DEC); } /**************************************************************************/ /* Show how to read IR and Full Spectrum at once and convert to lux */ /**************************************************************************/ uint16_t ir, full; void advancedRead(void) { // More advanced data read example. Read 32 bits with top 16 bits IR, bottom 16 bits full spectrum // That way you can do whatever math and comparisons you want! uint32_t lum = tsl.getFullLuminosity(); uint16_t ir, full; ir = lum &gt;&gt; 16; full = lum &amp; 0xFFFF; Serial.print(F(&quot;[ &quot;)); Serial.print(millis()); Serial.print(F(&quot; ms ] &quot;)); Serial.print(F(&quot;IR: &quot;)); Serial.print(ir); Serial.print(F(&quot; &quot;)); Serial.print(F(&quot;Full: &quot;)); Serial.print(full); Serial.print(F(&quot; &quot;)); Serial.print(F(&quot;Visible: &quot;)); Serial.print(full - ir); Serial.print(F(&quot; &quot;)); Serial.print(F(&quot;Lux: &quot;)); Serial.println(tsl.calculateLux(full, ir), 6); } /**************************************************************************/ /* Performs a read using the Adafruit Unified Sensor API. */ /**************************************************************************/ void unifiedSensorAPIRead(void) { /* Get a new sensor event */ sensors_event_t event; tsl.getEvent(&amp;event); /* Display the results (light is measured in lux) */ Serial.print(F(&quot;[ &quot;)); Serial.print(event.timestamp); Serial.print(F(&quot; ms ] &quot;)); if ((event.light == 0) | (event.light &gt; 4294966000.0) | (event.light &lt;-4294966000.0)) { /* If event.light = 0 lux the sensor is probably saturated */ /* and no reliable data could be generated! */ /* if event.light is +/- 4294967040 there was a float over/underflow */ Serial.println(F(&quot;Invalid data (adjust gain or timing)&quot;)); } else { Serial.print(event.light); Serial.println(F(&quot; lux&quot;)); } } int lightvalue; int NDVIred; int NDVIinfrared; int NDVI; boolean (hasrun) = false; /**************************************************************************/ /* Arduino loop function, called once 'setup' is complete (your own code should go here) */ /**************************************************************************/ void loop(void) { lightvalue = 255; //simpleRead(); //advancedRead(); //unifiedSensorAPIRead(); if(hasrun==false){ analogWrite(RED, lightvalue); advancedRead(); NDVIred = full; delay(5000); analogWrite(IR940,lightvalue); advancedRead(); NDVIinfrared=full; NDVI=(NDVIinfrared-NDVIred)/(NDVIinfrared+NDVIred); Serial.print(&quot;NDVI: &quot;); Serial.write(NDVIred); delay(1000); exit(0); } } </code></pre>
<p>You wrote:</p> <blockquote> <pre class="lang-cpp prettyprint-override"><code>Serial.print(&quot;NDVI: &quot;); Serial.write(NDVIred); </code></pre> </blockquote> <p>You are misusing here the <code>Serial.write()</code> method. This method is meant for sending raw bytes through the serial port. Since you are printing text, you probably want the numeric value <code>NDVIred</code> to be printed out as text, as a decimal number.</p> <p>For printing text, use <code>Serial.print()</code> and <code>Serial.println()</code>:</p> <pre class="lang-cpp prettyprint-override"><code>Serial.print(&quot;NDVI: &quot;); Serial.println(NDVIred); </code></pre>
93671
|power|battery|
Run Arduino Uno with battery AND use 5V output
2023-07-04T12:23:03.970
<p>Newbie here: I built a working binary clock with my Arduino UNO R3, see Picture 1. From my understanding the power supply for the Arduino itself is via USB, and I use the 5V output to supply power to the switch. Now, <strong>I would like the Arduino to run on battery and keep using its 5V power output</strong> - instead of only when it is connected to the PC.</p> <p><a href="https://i.stack.imgur.com/pzL7S.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/pzL7S.jpg" alt="setup powered via USB" /></a></p> <p>From what I gathered on the internet, e.g. <a href="https://www.instructables.com/Powering-Arduino-with-a-Battery/" rel="nofollow noreferrer">this page</a>, I can simply connect the + end of my battery to the Vin port and the - end to GND. However, none of the pages I found deal with what to do with the &quot;surrounding power infrastructure&quot;. Can I just keep it as is and use the wiring as in Picture 2 (USB is disconnected), i.e. is it safe to connect my 9V battery now? Or is there a better alternative?</p> <p><a href="https://i.stack.imgur.com/Gw4Ma.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Gw4Ma.jpg" alt="proposed setup running on battery" /></a></p> <p>Sorry for the beginner question. I am having so much fun learning with the Arduino (blasted through half the starter kit project handbook in just two days -&gt; this is my variant of the digital hourglass) and don't want it to go up in flames already.</p> <p>UPDATE: After the answers suggested that my idea should work, I tried it and, indeed, it works OK. I am getting a lot of Arduino resets/restarts though. Thanks for the replies!</p>
<p>You could certainly use a 9V battery into the VIN port on your Arduino, but the built-in power supply uses a &quot;linear voltage regulator&quot;, which is quite inefficient. If your goal is long battery life you'd be much better off with a buck style power supply or a switching power supply. Those are a LOT more efficient.</p> <p>You should be able to find modestly priced power supplies built for Adruino online that are a lot more efficient than the built-in supply.</p> <p>(And as mentioned, 9V batteries have a very small capacity. 6 AA or even C batteries would last a lot longer.)</p>
93682
|c++|
Are variables declared in main.cpp static, instance, or...?
2023-07-05T01:23:01.537
<p>Let's suppose you've just created a new Arduino project using PlatformIO, or an IDE like Sloeber. You now have a file named &quot;main.cpp&quot; with two functions (methods?):</p> <ul> <li>void setup()</li> <li>void loop()</li> </ul> <p>Now, suppose you follow Arduino coding norms, and stick something at the top like:</p> <pre><code>hd44780_I2Cexp lcd(0x27); </code></pre> <p>Is the hd44780_I2Cexp object instantiated by it static? Or is main.cpp #include'd into some class in a way that makes everything in it private or public members of that class?</p> <p>If they're instance methods, is it absolutely 100% guaranteed that the instance is, and forever shall be, a singleton? Or is there any conceivable scenario where there could be two simultaneous instances of it (say, if you were using both cores of an ESP32)?</p> <p>If it's an instance, but guaranteed to forever be singleton on any future platform that calls itself &quot;Arduino&quot;, is there any <em>need</em> to care about the distinction between &quot;instance member&quot; and &quot;static variable&quot; (in the context of main.cpp)?</p> <p>Should main.cpp &quot;really&quot; have a separate main.h file, and &quot;official&quot; <code>public:</code> and <code>private:</code> blocks for the sake of C++ linguistic purity, or would I just be creating real or potential problems for the sake of intellectual exercise and ideology?</p>
<p>Whatever you define outside of any function will be global, which is static - it lives for the duration of program execution - and visible to all compilation units that are bound into the eventual execution unit.</p> <p>If you also include the 'static' declaration ahead of the type, the variable will be file-level static, meaning it will be visibile only within the current file.</p> <p>This is standard C/C++ behavior for any data type - scalars; vectors, structs &amp; arrays; and objects (C++ only, of course).</p>
93699
|esp32|uart|code-optimization|platformio|buffer|
How to optimize checking for specific string in a UART stream
2023-07-06T13:25:12.570
<p>I want to check for specific string (like &quot;RecordStart&quot;) in a UART stream (115 200 baud 8N1) from a <a href="https://www.foxeer.com/foxeer-4k-ambarella-a12-hd-camera-uav-pwm-remote-control-wifi-distortionless-lens-tv-out-micro-hdmi-g-220" rel="nofollow noreferrer">camera</a>, to know when it is recording or not/if there is an SD. I am using an ESP32-WROOM-32UE with 16MB flash. I wired the Tx from the camera to one of the pin of the ESP. The ESP32 is programmed with VsCode (platformIO) through Arduino framework. I am using freeRTOS.</p> <p>The thing is, &quot;RecordStart&quot; or &quot;RecordStop&quot; or other strings, appear just one time. Sometimes (when the camera is powering on), there are many many strings sended, very fast. So, from time to time, I lose some bytes and I can't find the strings I am looking for. I would like to optimize my code to never miss a string.</p> <p><em>How the code works ?</em> If there is at least 1 byte in the serial buffer, the <em>taskUART</em> priority is set to 2 (while other tasks are priority 1. If a null character is detected, the <em>message_UARTcam</em> buffer starts to be filled. Then, each time a byte enters the buffer, I am checking if the buffer contains the strings I am looking for. It is working quite well but sometimes, I lose some bytes and the strings are not detected. I think It is because many other tasks are running and the serial buffer fills up faster than it empties. Increase temporarily the priority of the UART task improves the detection but I am still missing some bytes.</p> <p><em>The code:</em></p> <pre><code>void taskUART(void *parameter) { while (1) { if (SerialPortCam.available() &gt; 0) { vTaskPrioritySet(nullptr, 2); char incomingChar = SerialPortCam.read(); // Serial.write(incomingChar); if (flagNullChar == 1 || bufferIndex_UARTcam &gt; 0 &amp;&amp; bufferIndex_UARTcam &lt; BUFFER_LEN_UART_CAM) { message_UARTcam += incomingChar; // Serial.println(message); if (message_UARTcam.indexOf(stringStart_app) != -1 || message_UARTcam.indexOf(stringStart_button) != -1) { // Serial.println(&quot;Start recording&quot;); SD_UARTcam = 1; record_UARTcam = 1; bufferIndex_UARTcam = 0; message_UARTcam = &quot;&quot;; } else if (message_UARTcam.indexOf(stringStop) != -1) { // Serial.println(&quot;Stop recording&quot;); record_UARTcam = 0; bufferIndex_UARTcam = 0; message_UARTcam = &quot;&quot;; } else if (message_UARTcam.indexOf(stringSdError) != -1) { // Serial.println(&quot;SD error&quot;); SD_UARTcam = 0; record_UARTcam = 0; bufferIndex_UARTcam = 0; message_UARTcam = &quot;&quot;; } else if (message_UARTcam.indexOf(stringSdInitOk) != -1) { // Serial.println(&quot;SD init OK&quot;); SD_UARTcam = 1; bufferIndex_UARTcam = 0; message_UARTcam = &quot;&quot;; } else if (message_UARTcam.indexOf(stringSdRemoved) != -1) { // Serial.println(&quot;SD removed&quot;); SD_UARTcam = 0; record_UARTcam = 0; bufferIndex_UARTcam = 0; message_UARTcam = &quot;&quot;; } bufferIndex_UARTcam++; flagNullChar = 0; } if (incomingChar == 0x00) { flagNullChar = 1; message_UARTcam = &quot;&quot;; bufferIndex_UARTcam = 0; } } else { vTaskPrioritySet(nullptr, 1); } } } </code></pre> <p><em>Camera output example:</em></p> <pre><code>␛[0;36m[00105849][CA9] ␀[App - Connected] &lt;OnMessage&gt; Received msg: 0xE001000C (param1 = 0x0 / param2 = 0x0)␛[0m ␛[0m[00105849][CA9] ␀RecCapState:0 RecCurrMode:0 RecNextMode:0 GFlags:0X7 Flags:0 StreamType:0␛[0m ␛[0m[00105849][CA9] ␀[App - Widget] &lt;Off&gt; widgetId: -1␛[0m ␛[0;33m[00105849][CA9] ␀[App_Glob_PWM_Buzzer] PWM Buzzer : 2␛[0m ␛[0m[00105849][CA9] ␀[App - ButtonOp] &lt;MgrTask&gt; Received msg: 0x0 (Param1 = 0x0 / Param2 = 0x0)␛[0m ␛[0m[00105849][CA9] ␀[App - ButtonOp] &lt;MgrTask&gt; Received msg: 0x1 (Param1 = 0x0 / Param2 = 0x0)␛[0m ␛[0m[00105899][CA9] ␀[rec_connected_cam_record_start] Start␛[0m ␛[0m[00105899][CA9] ␀[App - Connected] &lt;RecordStart&gt; REC_CONNECTED_CAM_RECORD_START␛[0m ␛[0m[00105899][CA9] ␀Dechi.motion_detec: 0␛[0m ␛[0m[00105899][CA9] ␀[Applib - ExtendEnc] &lt;_ExtendEnc_SetEnableStatus&gt; Enable flag: 0␛[0m ␛[0m[00105899][CA9] ␀[AppLib - MuxMp4] &lt;SetTrickRecDivisor&gt; Cur TrickRecDivisor: 1, New TrickRecDivisor: 1␛[0m ␛[0;34m[00105899][CA9] ␀[App - Sensor] &lt;GetVinMode&gt; Vin Mode = 11␛[0m </code></pre>
<p>Here is an idea that <em>may</em> work: instead of buffering the input stream and comparing the buffer with the search string, you could do the comparison on the fly, as you receive the characters. Then you have no buffering at all, and no time spent in scanning through the buffer.</p> <p>Below is a function that searches for the <code>&quot;RecordStart&quot;</code> marker, while being fed one character at a time. This function remembers how many correct characters it has received so far (this is the static variable <code>pos</code>), and updates this count on each received character. It returns <code>true</code> when it has just detected the marker, and <code>false</code> otherwise:</p> <pre class="lang-cpp prettyprint-override"><code>bool marker_found(int c) { const char marker[] = &quot;RecordStart&quot;; // search string static int pos = 0; // correct characters received so far if (c == -1) return false; // shortcut for a common case if (c == marker[pos]) { pos++; // count a correct character if (marker[pos] == '\0') { // we got the complete string pos = 0; // reset for next time return true; // report success } } else if (c == marker[0]) { pos = 1; // we have the initial character again } else { pos = 0; // we received a wrong character } return false; } </code></pre> <p>You would use it like this:</p> <pre class="lang-cpp prettyprint-override"><code>if (marker_found(SerialPortCam.read())) { // handle the incoming record } </code></pre> <p>Note that you do not need to test for <code>SerialPortCam.available() &gt; 0</code>, as this is already handled by <code>marker_found()</code>.</p>
93706
|i2c|attiny85|arduinoisp|
Can I program ATTINY using Arduino as ISP whilst having other I2C devices connected?
2023-07-06T15:27:28.190
<p>I have an SMD ATTINY that I'm using for a project. Attached to it are 3 I2C devices. When programming it using an Arduino as an ISP, can I have those devices attached? Ie, do I have to program the ATTINY and then solder it on my board or can I solder it and the program (and re-program if necessary).</p>
<p>Yes, the slave devices shouldn't respond unless addressed. When programming, data will obviously be on the lines however the probability of this data accidentally containing the right sequence to correctly query a slave is minimal.</p>
93724
|programming|time|oled|delay|seeeduino-xiao|
Functions delaying gesture sensor recognition
2023-07-07T14:29:47.893
<p>I am working on a simple little robot to cure my boredom and all it has is a 64 x 32 OLED for the eyes, and a PAJ7620 Gesture recognition sensor with a Seeeduino Xiao as the main board.</p> <p>Basically, when people swipe above the head where the sensor is, the robot will show the heart eyes. There are different reactions for different actions and all this is controlled through functions. When the sensor does not detect anything, the robot is supposed to cycle through a certain void which is determined based on how much it 'likes' the person.</p> <p>Right now though, it just cycles through the function and does not respond to the sensor. My code is <em>very</em> inefficient because of all the functions, but it makes it more readable and more easily editable. With all my functions, the gesture sensor takes too long to respond to the actions.</p> <p>What can I do to fix this? Can someone please help or give advice on how I can improve my code?</p> <pre class="lang-c prettyprint-override"><code> #include &lt;Arduino.h&gt; #include &lt;U8g2lib.h&gt; #include &lt;Wire.h&gt; #include &lt;DFRobot_PAJ7620U2.h&gt; int like_score = 3;//Score for how much the bot likes you: this will impact which voids are used. int max_like_score = 17; char buffer[9]; unsigned long previousMillis = 0; const long interval = 1000; DFRobot_PAJ7620U2 paj; U8G2_SSD1306_64X32_1F_F_HW_I2C u8g2(U8G2_R0, /* reset=*/U8X8_PIN_NONE); // fonts https://github.com/olikraus/u8g2/wiki/fntlistall#4-pixel-height void setup(void) { u8g2.begin(); Serial.begin(115200); delay(300); u8g2.clearBuffer(); Serial.println(&quot;Gesture recognition system base on PAJ7620U2&quot;); while (paj.begin() != 0) { Serial.println(&quot;initial PAJ7620U2 failure! Please check if all the connections are fine, or if the wire sequence is correct?&quot;); delay(500); } Serial.println(&quot;PAJ7620U2 init completed, start to test the gesture recognition function&quot;); paj.setGestureHighRate(true); } void normalL() { //normal forward expression u8g2.clearBuffer(); // clear the internal memory u8g2.drawBitmap(0, 0, 8, 32, normal); u8g2.sendBuffer(); } void blinkL() { //blinks u8g2.clearBuffer(); // clear the internal memory u8g2.drawBitmap(0, 0, 8, 32, blink); u8g2.sendBuffer(); } void left() { //looks left u8g2.clearBuffer(); // clear the internal memory u8g2.drawBitmap(0, 0, 8, 32, blinkleft); u8g2.sendBuffer(); } void right() { //looks right u8g2.clearBuffer(); // clear the internal memory u8g2.drawBitmap(0, 0, 8, 32, blinkright); u8g2.sendBuffer(); } void angryL() { //angry u8g2.clearBuffer(); // clear the internal memory u8g2.drawBitmap(0, 0, 8, 32, angry); u8g2.sendBuffer(); } void loveL() { //in love u8g2.clearBuffer(); // clear the internal memory u8g2.drawBitmap(0, 0, 8, 32, love); u8g2.sendBuffer(); } void sleepL() { //sleeping u8g2.clearBuffer(); // clear the internal memory u8g2.drawBitmap(0, 0, 8, 32, sleep); u8g2.sendBuffer(); } void susL() { //suspicious u8g2.clearBuffer(); // clear the internal memory u8g2.drawBitmap(0, 0, 8, 32, sus); u8g2.sendBuffer(); } void stunL() { //looks stunned u8g2.clearBuffer(); // clear the internal memory u8g2.drawBitmap(0, 0, 8, 32, stun); u8g2.sendBuffer(); } void upL() { //Looks up u8g2.clearBuffer(); // clear the internal memory u8g2.drawBitmap(0, 0, 8, 32, up); u8g2.sendBuffer(); } void gleeL() { u8g2.clearBuffer(); // clear the internal memory u8g2.drawBitmap(0, 0, 8, 32, glee); u8g2.sendBuffer(); } void randomEx() { int rand = random(1, 8); if (rand == 1) { normalL(); } else if (rand == 2) { left(); } else if (rand == 3) { right(); } else if (rand == 4) { angryL(); } else if (rand == 5) { loveL(); } else if (rand == 6) { susL(); } else if (rand == 7) { upL(); } else if (rand == 8) { gleeL(); } } void likeRoutine() { normalL(); delay(random(1000, 6500)); blinkL(); delay(90); normalL(); delay(random(1000, 4500)); randomEx(); delay(random(1000, 4500)); blinkL(); delay(90); loveL(); delay(random(2500, 4000)); blinkL(); delay(90); } void kindofLikeRoutine() { normalL(); delay(random(1000, 7000)); blinkL(); delay(90); normalL(); delay(random(1000, 4500)); randomEx(); delay(random(1000, 4500)); blinkL(); delay(90); loveL(); delay(random(1000, 3000)); blinkL(); delay(90); } void dislikeRoutine() { normalL(); delay(random(1000, 7000)); blinkL(); delay(90); normalL(); delay(random(1000, 6500)); randomEx(); delay(random(1000, 4000)); blinkL(); delay(90); angryL(); delay(random(1000, 3000)); blinkL(); delay(90); } void hateRoutine() { angryL(); delay(random(1000, 5000)); blinkL(); delay(90); normalL(); delay(random(1000, 6500)); randomEx(); delay(random(1000, 4000)); blinkL(); delay(90); angryL(); delay(random(1000, 3000)); blinkL(); delay(90); } void loop(void) { DFRobot_PAJ7620U2::eGesture_t gesture = paj.getGesture(); if (gesture != paj.eGestureNone) { String description = paj.gestureDescription(gesture); //Convert gesture number into string description if (gesture == 256) { //wave gleeL(); delay(random(1000, 4500)); } else if (gesture == 2 &amp;&amp; like_score &lt; max_like_score) { //pet blinkL(); delay(90); loveL(); like_score++; Serial.println(like_score); delay(random(1000, 3000)); if (like_score == max_like_score) { blinkL(); delay(90); loveL(); delay(random(1000, 3000)); } } else if (gesture == 16 &amp;&amp; like_score &lt;= max_like_score) { //thump stunL(); like_score--; Serial.println(like_score); delay(random(1000, 4000)); angryL(); delay(random(1000, 3000)); } else if (gesture == 128) { u8g2.clearBuffer(); u8g2.setFont(u8g2_font_t0_11_tf); // choose a suitable font dtostrf(like_score, 6, 0, buffer); String scoreStr = String(buffer); u8g2.drawStr(0, 20, scoreStr.c_str()); u8g2.sendBuffer(); delay(random(2000, 3500)); } } else { if (like_score &gt;= 11) { likeRoutine(); } else if (like_score &gt; 7 &amp;&amp; like_score &lt; 11) { kindofLikeRoutine(); } else if (like_score &gt; 0 &amp;&amp; like_score &lt; 7) { dislikeRoutine(); } else if (like_score &lt; 0) { hateRoutine(); } } } </code></pre>
<p>The code is being slowed down by the <code>delay()</code> function because it is a <code>blocking</code> function.</p> <p>The delay function does not exit until delay time passes, so no other functions can run, such as sensor reading.</p> <p>The simplest solution for your code may be an FSM library (finite state machine). It would look after all of the timing for you.</p> <p>You could also replace the <code>delay()</code> functions with your own delay function, something like</p> <pre class="lang-cpp prettyprint-override"><code> void myDelay(int totalDelay) { for (i = 0; i &lt; totalDelay/100; i++) { // do some housekeeping here, like reading sensors delay(100); // this blocks for only 1/10 of a second } // adjust the delay value if housekeeping takes a lot of time } </code></pre> <p>The delay gets broken into a lot of small delays with time to do other things in between.</p> <p>Another way is to check at the begining of <code>loop()</code> to see how much time has elapsed. See blinkWithoutDelay example code in the Arduino IDE.</p> <p>Here is an example in a simulator that may help you.</p> <p><a href="https://wokwi.com/projects/362275278547275777" rel="nofollow noreferrer">https://wokwi.com/projects/362275278547275777</a></p>
93734
|arduino-nano|uploading|avrdude|ch340|
Arduino Nano uploading problems
2023-07-08T15:24:38.027
<p>I am having trouble uploading code to my Arduino Nano. It has been very trusty in the past, but I am getting this new error when uploading any code to it: <code>avrdude: ser_open(): can't set com-state for &quot;\\.\COM15&quot;</code></p> <p>This happened a while ago on my Windows 11 Laptop, and I was unable to resolve it, and now it has just started on my Windows 10 desktop.</p> <p>I tried disabling and re-enabling the CH340 in device manager, restarted my computer, and uninstalled the CH340. After uninstalling it, it has dissapeared and does not even show up in Device Manager at all.</p> <p>If anybody could provide some help explaining how to make it show up in Device Manager again, and also make it uploadable, I would greatly appreciate it!</p> <p>Thank you in advance</p>
<p>Apparently there was an update in ch340 drivers early in 2023 and it broke something for counterfeit ch340. Solution is using older version of the driver (and possibly disabling automatic updates for the drivers in the Windows).</p> <p><a href="https://github.com/SHWotever/SimHub/wiki/Arduino---Counterfeit-Fake-CH340G-chips-driver-issues" rel="nofollow noreferrer">Issue description and solution found on github</a>:</p> <blockquote> <p>Rollback to an older driver manually :</p> <p>Unfortunately since the incompatible driver is delivered through windows update it is harder to keep an older driver installed :</p> <p>Recommended : Block windows drivers update so the newest driver won't get installed automatically: <a href="https://www.makeuseof.com/windows-stop-automatic-driver-updates" rel="nofollow noreferrer">https://www.makeuseof.com/windows-stop-automatic-driver-updates</a> (note: while this is required to be able to install and keep the older ch340g driver but this will affect any of your future devices)</p> <p>Reinstall an older driver here : <a href="https://github.com/SHWotever/SimHub/files/11564977/CH341SER.zip" rel="nofollow noreferrer">01/30/2019, 3.5.2019.1 CH341SER driver</a></p> </blockquote>
93735
|arduino-uno|i2c|lcd|
LCD I2C connection problems
2023-07-08T17:31:23.963
<p>I am hoping there is a simple fix to this problem.</p> <p>I am playing around with a 16x2 lcd with a I2C connector attached. I wired it up to an elegoo uno R3.</p> <p>I started with some code I've used before and ended up with one row of the LCD fully lit and the other dark.</p> <p>After a ton of trouble shooting, I can not get the LCD to show anything but one lit and one dark row.</p> <p><a href="https://i.stack.imgur.com/WeshD.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/WeshD.jpg" alt="arduino with lcd attached" /></a></p> <p>In this image:</p> <p>Power: 5V, 1.5A</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>Pin</th> <th>LCD</th> <th>Uno</th> </tr> </thead> <tbody> <tr> <td>SCL</td> <td>SCL</td> <td>SCL</td> </tr> <tr> <td>SCA</td> <td>SDA</td> <td>SDA</td> </tr> <tr> <td>+</td> <td>VCC</td> <td>5V</td> </tr> <tr> <td>gnd</td> <td>gnd</td> <td>gnd</td> </tr> </tbody> </table> </div> <p>I've also tried:</p> <ul> <li>putting the SDA to A4 and the SCL to A5</li> <li>Using different power supplies</li> <li>Powering from the USB connector</li> </ul> <p>And I've tried several of the libraries available</p> <p>They are all variations of the following from the <a href="https://github.com/adafruit/Adafruit_LiquidCrystal" rel="nofollow noreferrer">Adafruit_LiquidCrystal</a> library:</p> <pre><code>#include &lt;Wire.h&gt; #include &lt;LiquidCrystal_I2C.h&gt; // Set the LCD address to 0x27 for a 16 chars and 2 line display LiquidCrystal_I2C lcd(0x27, 16, 2); void setup() { // initialize the LCD lcd.begin(); // Turn on the blacklight and print a message. lcd.backlight(); lcd.print(&quot;Hello, world!&quot;); } void loop() { // Do nothing here... } </code></pre> <p>No matter what I do the display does not change.</p>
<p>Some common problems with LCD displays which incorporate an I2C backpack include:</p> <ol> <li>Not using the correct I2C address for the I2C backpack. Use an I2C scanner to discover the correct address.</li> <li>Mixing voltages without proper level shifting, say using a 5v display with a 3.3v MCU</li> <li>Failing to adjust the contrast potentiometer</li> <li>Some I2C backpacks may use a non-standard pin allocation which may be corrected by specifying a pin mapping in the constructor to the display library. Fortunately, this is rare.</li> <li>Using code samples intended for a different variant of the library supporting the display. Always use a basic test sketch which is packaged with the chosen library to verify the performance of the display.</li> </ol>
93748
|arduino-nano|servo|
Arduino Servo MG90S not moving
2023-07-09T14:13:43.600
<p><a href="https://i.stack.imgur.com/yLqB1.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/yLqB1.png" alt="enter image description here" /></a>I'm new with arduino (nano). I am having problems with Servo MG90S, I cant make it move. Im doing the easiest test, Servo cables connected:</p> <p>Brown -&gt; gnd<br /> Red -&gt; 5v<br /> Orange -&gt; pin 9</p> <p>my arduino code is:</p> <pre><code>#include &lt;Servo.h&gt; Servo servo; const int servoPin = 9; void setup() { servo.attach(servoPin); Serial.begin(9600); } void loop() { servo.write(40); delay(2000); servo.write(0); delay(2000); } </code></pre> <p>As you see its a super simple example, but the result is the servo vibrating slightly.</p> <p>Extra data: the servo start vibrating with the <code>servo.attach(servoPin);</code> it doesnt matters if I set the <code>servo.write(40);</code></p>
<p>Okay, so my first answer is WRONG. The reason being is because the MG90S and the SG90 (which are very similar servos, except the gearing and some others) <strong>CAN</strong> run off that Arduino. As this article shows: <a href="https://www.hibit.dev/posts/101/how-to-control-servo-motor-with-arduino" rel="nofollow noreferrer">How to control the MG90S with the Nano</a>. However, it <em>IS</em> best to run that servo off a separate power supply (5V). The issue lies within your wiring. Somehow, there is some miscommunication between us, you, and the Arduino.</p>
93755
|sd-card|data-type|
Read one byte from file and convert to decimal
2023-07-09T22:50:57.823
<p>Ok, I'm fairly new to Arduino and I'm trying to read bytes from a file in an SD card and convert to integer values (0-255).</p> <p>I have a file, with 1 byte on it (128 int value, created in Python, can provide the code if necessary) and the hex dump (binary mode) is:</p> <pre><code>xxd -b single_byte.dat 00000000: 10000000 </code></pre> <p>So far so good, right? So I was expecting to read this byte from the file (SD card) and then convert back to 128 value. This is my Arduino code:</p> <pre><code>#include &lt;SPI.h&gt; #include &lt;SD.h&gt; // set up variables using the SD utility library functions: Sd2Card card; SdVolume volume; SdFile root; const int chipSelect = 4; void setup() { // Open serial communications and wait for port to open: Serial.begin(9600); while (!Serial) { ; } delay(100); Serial.print(&quot;\nInitializing SD card...&quot;); if (!card.init(SPI_HALF_SPEED, chipSelect)) { Serial.println(&quot;initialization failed. Things to check:&quot;); Serial.println(&quot;* is a card inserted?&quot;); Serial.println(&quot;* is your wiring correct?&quot;); Serial.println(&quot;* did you change the chipSelect pin to match your shield or module?&quot;); while (1); } else { Serial.println(&quot;Wiring is correct and a card is present.&quot;); } // print the type of card Serial.println(); Serial.print(&quot;Card type: &quot;); switch (card.type()) { case SD_CARD_TYPE_SD1: Serial.println(&quot;SD1&quot;); break; case SD_CARD_TYPE_SD2: Serial.println(&quot;SD2&quot;); break; case SD_CARD_TYPE_SDHC: Serial.println(&quot;SDHC&quot;); break; default: Serial.println(&quot;Unknown&quot;); } // Now we will try to open the 'volume'/'partition' - it should be FAT16 or FAT32 if (!volume.init(card)) { while (1); } File file; byte one_byte; int dec_value; file = SD.open(&quot;single_byte.dat&quot;, FILE_READ); one_byte = file.read(); file.close(); dec_value = int(one_byte); Serial.println(dec_value, DEC); } void loop(void) { } </code></pre> <p>I was expecting the output to be 128.</p> <p>However I get:</p> <p><a href="https://i.stack.imgur.com/ESQxl.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ESQxl.png" alt="Actual output" /></a></p> <p>What am I missing? (yes, I tried generating the .dat file with big-endian encoding, same result)</p>
<p>Ok, I got it working now, here's what was happening:</p> <p>Turns out the file wasn't being opened. Why? seems like there's a limitation on the filename length, I noticed this after adding the lines:</p> <pre><code>root.openRoot(volume); // list all files in the card with date and size root.ls(LS_R | LS_DATE | LS_SIZE) </code></pre> <p>And sure enough my file was not detected as <strong>single_byte.dat</strong> but it was something like: <strong>single_~.dat</strong> so I renamed the file to <strong>test.dat</strong> and tada! code now works like a charm.</p> <p>I guess I overlooked this restriction on the documentation, so keep this in mind when you use an SD card.</p> <p>Also, make sure to check if you are really opening your file because no exception will be thrown if you reference an uninitialized file pointer I guess.</p> <p>Just make sure to have:</p> <pre><code>file = SD.open(filename, FILE_READ); if(file){ // Do things here. } else{ Serial.println(&quot;You're out of luck: Can't open file&quot;); } </code></pre> <p>Ok, there goes my Sunday. Thanks all for reading!!!</p>
93773
|serial|softwareserial|serial-data|
HardwareSerial and SoftwareSerial not compatible
2023-07-11T19:31:11.940
<p>The HardwareSerial requires to run an interrupt to store received bytes in the buffer. Look at <a href="https://github.com/arduino/ArduinoCore-avr/blob/master/cores/arduino/HardwareSerial_private.h" rel="nofollow noreferrer">this</a> file from the Arduino Core. If I am now constantly receiving and writing on the Software Serial, the data from the HardwareSerial cannot be buffered, since external interrupts are higher priority.</p> <p>In my application, I need to constantly listen to the SoftwareSerial and respond immediately to incoming data (actually inside the receive interrupt of the SoftwareSerial, so its modified), so the SoftwareSerial has higher priority. But when I do this, I lose data on the HardwareSerial.</p> <p>Is there any way to circumvent this limitation, without disabling any interrupts or getting a chip with more UART ports?</p> <p>EDIT: the actual interrupt vector is <a href="https://github.com/arduino/ArduinoCore-avr/blob/eabd762a1edcf076877b7bec28b7f99099141473/cores/arduino/HardwareSerial0.cpp" rel="nofollow noreferrer">here</a></p> <p>EDIT2: This is question is not answered by the answers in my previous question. It is clearly a fact that HardwareSerial needs its receive interrupt to store data in a buffer. My question now is how I can still use the SoftwareSerial while it is constantly receiving.</p>
<p>If you are sending something in SoftwareSerial ISR handler that means ISRs are disabled and you are blocking other ISRs being called (if needed).</p> <p>If you're using some crazy slow baudrate like 9600 then it means over 1 millisecond per character sent and during that time you might be missing other interrupts calls (millis, HW serials). If there is only one character, it's not problem, it'll be handled after interrupts are enabled again, but if there will be second or more character, previous are lost, as the've never been readed out from the UDR register (that should set flag for buffer overrun or how it's called).</p> <p>If your Hw serial has some nice speed like 115200, you can lose up to 12 characters during sending single characted on software serial with speed 9600</p> <p>The cli() in <a href="https://github.com/arduino/ArduinoCore-avr/blob/master/libraries/SoftwareSerial/src/SoftwareSerial.cpp#L436C22-L436C22" rel="nofollow noreferrer">software serial library</a> but as you wrote it's called from ISR handler and the ISRs are disabled anyway already during whole ISR handler</p>
93776
|esp8266|arduino-ide|led|nodemcu|button|
ESP8266 seems to be killing a while loop
2023-07-11T20:57:42.893
<p>When i was testing out a program I found a strange behavior of esp8266</p> <p>It seems to get out of a while loop even when there's no option of getting out on code</p> <p>I don't know if these are related but here's the code (the program is just two different visual patterns of leds toggled by a button)</p> <pre><code>#define led1 D0 #define led2 D1 #define led3 D2 #define led4 D3 #define button D7 unsigned long pressedButton; bool change = 0; unsigned long previousTime; unsigned int difference; void setup() { pinMode(led1, OUTPUT); pinMode(led2, OUTPUT); pinMode(led3, OUTPUT); pinMode(led4, OUTPUT); pinMode(button, INPUT_PULLUP); } void loop(){ digitalWrite(led1, LOW); digitalWrite(led2, LOW); digitalWrite(led3, LOW); //when the while loop change, this should delete interference digitalWrite(led4, LOW); previousTime = millis(); while (!change){ //default visual pattern of leds difference = millis()-previousTime; if (!digitalRead(led1) &amp;&amp; difference&gt;=200){ digitalWrite(led1, HIGH); } if (!digitalRead(led2) &amp;&amp; difference&gt;=400){ digitalWrite(led2, HIGH); } if (!digitalRead(led3) &amp;&amp; difference&gt;=600){ digitalWrite(led3, HIGH); } if (!digitalRead(led4) &amp;&amp; difference&gt;=800){ //after here, all the leds should be HIGH digitalWrite(led4, HIGH); } if (digitalRead(led4) &amp;&amp; difference&gt;=1000){ digitalWrite(led4, LOW); } if (digitalRead(led3) &amp;&amp; difference&gt;=1200){ digitalWrite(led3, LOW); } if (digitalRead(led2) &amp;&amp; difference&gt;=1400){ digitalWrite(led2, LOW); } if (digitalRead(led1) &amp;&amp; difference&gt;=1600){ //after here, all the leds should be LOW digitalWrite(led1, LOW); previousTime = millis(); } if (!digitalRead(button) &amp;&amp; millis()-pressedButton&gt;200){ //check if button was pressed to break while loop pressedButton = millis(); break; } } while (change){ //alternative of visual pattern of leds difference = millis()-previousTime; if (!digitalRead(led1) &amp;&amp; difference&gt;=200){ digitalWrite(led1, HIGH); digitalWrite(led4, HIGH); digitalWrite(led2, LOW); digitalWrite(led3, LOW); } if (digitalRead(led1) &amp;&amp; difference&gt;=400){ digitalWrite(led1, LOW); digitalWrite(led4, LOW); digitalWrite(led2, HIGH); digitalWrite(led3, HIGH); previousTime = millis(); } //if (!digitalRead(button) &amp;&amp; millis()-pressedButton&gt;=200){ //check if button was pressed to break while loop // pressedButton = millis(); // break; //} } change = !change; //after a break in one of the while loops, this will make the program go to the other while loop } </code></pre> <p>Is there something wrong with the code? Here is a link of a video of the behavior for more details <a href="https://drive.google.com/file/d/1822MHNGQn-A2-HGHhRXz_8xydz-wM4Ha/view?usp=sharing" rel="nofollow noreferrer">https://drive.google.com/file/d/1822MHNGQn-A2-HGHhRXz_8xydz-wM4Ha/view?usp=sharing</a></p>
<p>You can't trap an ESP in a while loop like that. There are things it needs to get back to main and do between loops. Instead, let the loop function be your loop. Make the while statements if statements and where you have break, that's where you change the change variable. Put the code at the top in an if statement that checks to see if change has changed.</p> <pre><code>#define led1 D0 #define led2 D1 #define led3 D2 #define led4 D3 #define button D7 unsigned long pressedButton; bool change = 0; bool oldChange = 1; unsigned long previousTime; unsigned int difference; void setup() { pinMode(led1, OUTPUT); pinMode(led2, OUTPUT); pinMode(led3, OUTPUT); pinMode(led4, OUTPUT); pinMode(button, INPUT_PULLUP); } void loop() { if (change != oldChange) { digitalWrite(led1, LOW); digitalWrite(led2, LOW); digitalWrite(led3, LOW); //when the while loop change, this should delete interference digitalWrite(led4, LOW); previousTime = millis(); oldChange = change; } if (!change) { //default visual pattern of leds difference = millis() - previousTime; if (!digitalRead(led1) &amp;&amp; difference &gt;= 200) { digitalWrite(led1, HIGH); } if (!digitalRead(led2) &amp;&amp; difference &gt;= 400) { digitalWrite(led2, HIGH); } if (!digitalRead(led3) &amp;&amp; difference &gt;= 600) { digitalWrite(led3, HIGH); } if (!digitalRead(led4) &amp;&amp; difference &gt;= 800) { //after here, all the leds should be HIGH digitalWrite(led4, HIGH); } if (digitalRead(led4) &amp;&amp; difference &gt;= 1000) { digitalWrite(led4, LOW); } if (digitalRead(led3) &amp;&amp; difference &gt;= 1200) { digitalWrite(led3, LOW); } if (digitalRead(led2) &amp;&amp; difference &gt;= 1400) { digitalWrite(led2, LOW); } if (digitalRead(led1) &amp;&amp; difference &gt;= 1600) { //after here, all the leds should be LOW digitalWrite(led1, LOW); previousTime = millis(); } if (!digitalRead(button) &amp;&amp; millis() - pressedButton &gt; 200) { //check if button was pressed to break while loop pressedButton = millis(); change = true; } } if (change) { //alternative of visual pattern of leds difference = millis() - previousTime; if (!digitalRead(led1) &amp;&amp; difference &gt;= 200) { digitalWrite(led1, HIGH); digitalWrite(led4, HIGH); digitalWrite(led2, LOW); digitalWrite(led3, LOW); } if (digitalRead(led1) &amp;&amp; difference &gt;= 400) { digitalWrite(led1, LOW); digitalWrite(led4, LOW); digitalWrite(led2, HIGH); digitalWrite(led3, HIGH); previousTime = millis(); } } change = false } </code></pre>
93782
|arduino-mega|shields|
Stack Mega Shield
2023-07-12T08:11:54.740
<p>I need to support 18 push buttons and 66 IR sensors on my Arduino Mega (model railway). I have a Mega Sensor Shield, but won't have enough pins for all the sensors. Can I get a second sensor shield and nest it some way?</p> <p><a href="https://www.aliexpress.com/item/1005004554959620.html?spm=a2g0o.order_list.order_list_main.31.1cda18022wJnOM" rel="nofollow noreferrer">https://www.aliexpress.com/item/1005004554959620.html?spm=a2g0o.order_list.order_list_main.31.1cda18022wJnOM</a></p>
<p>For a model railway, this may not work as well as you are expecting. Sending 66 sensors values and 18 push-buttons along long cable lengths, as may be expected for a model railway, could introduce noise which would give bogus readings. The noise in long, adjacent, cables could be from one cable inducing a voltage in its neighbour, or simply from the railway operations themselves.</p> <p>It may be better to use something like <a href="https://en.wikipedia.org/wiki/RS-485" rel="nofollow noreferrer">RS485</a> which is a balanced protocol. That is, of the two data wires connecting nodes, one is positive and one is negative simultaneously, for a signal to be considered genuine. Noise would tend to influence the cables in the same direction (eg. both positive) and would thus be discarded.</p> <p>As described in the <a href="https://en.wikipedia.org/wiki/RS-485" rel="nofollow noreferrer">Wikipedia article</a>, RS485 is used in aircraft for reliability. The wiring is minimal: two wires for data, plus an earth wire. You would also need 5V power available at the nodes.</p> <p>What I would suggest here is a series of nodes, spread around your railway layout. Each node could be an inexpensive Atmeg328P processor (around $3 on eBay) with a couple of supporting resistors and capacitors. You would use 3 pins for the RS485 (transmit, receive and enable) which would leave 17 inputs for your sensors and switches per node. Thus, around 5 nodes.</p> <p>You would keep the cabling for the sensors running to each node as short as possible, to reduce noise. Maybe use shielded cable.</p> <p>I wrote an <a href="https://github.com/nickgammon/RS485_non_blocking" rel="nofollow noreferrer">RS485 non-blocking library</a> - available on Github.</p> <p>There are some explanations about using it <a href="https://www.gammon.com.au/forum/bbshowpost.php?bbsubject_id=11428" rel="nofollow noreferrer">on my website</a> most of which is also on the Github page.</p> <p>Basically what you would do is give each node an address (stored in EEPROM) and then have a master query each node in turn for the values on its sensors or switches. The node would reply, and then the master could move onto the next one.</p> <hr /> <p>I realise this isn't directly answering the question about the Mega shield, but I am trying to answer the underlying problem of how to connect 84 sensors and switches to one Arduino reliably.</p>
93783
|serial|esp8266|softwareserial|gsm|sim800|
sim800l gsm module response isn't completed
2023-07-12T13:52:17.360
<p>I am using the <code>sim800l gsm module</code> with <code>nodemcu esp8266</code> and comunicating with it using AT+ commands. The module is working correctly but I am trying to use the command <code>AT+CLCC</code> to get all the current calls' state but it responds with only the first call information and a part of the second call.</p> <p>This is the response while there are two active calls</p> <pre><code>15:37:19.156 -&gt; AT+CLCC 15:37:19.156 -&gt; +CLCC: 1,0,1,0,0,&quot;+0123456789&quot;,145,&quot;name&quot; 15:37:19.156 -&gt; 15:37:19.156 -&gt; +CLCC: 2, </code></pre> <p>I think it is the Serial buffer's problem because the size of the serial buffer is 64 bytes and the response is more than that but I don't know how to handle that</p> <p>I hope someone can help.</p> <p>EDIT: this is the code i am using</p> <pre><code>#include &lt;SoftwareSerial.h&gt; #include &lt;cstring&gt; #include &lt;Arduino.h&gt; #define simTX D3 #define simRX D4 SoftwareSerial sim800l(simRX, simTX); //RX, TX void setup() { Serial.begin(115200); //Begin serial communication with Arduino and Arduino IDE (Serial Monitor) sim800l.begin(115200); //Begin serial communication with Arduino and SIM800L } void loop() { updateSerial(); } //Start // this method takes input from the serial monitor the pass it to sim800l via serial communication void updateSerial() { delay(500); while (Serial.available()) { sim800l.write(Serial.read()); //Forward what Serial received to Software Serial Port } while (sim800l.available()) { Serial.write(sim800l.read()); //Forward what Software Serial received to Serial Port } } //End </code></pre>
<p>Just for someone in the future who is having the same issue.</p> <p>the problem was because of the boadrate 115200 is pretty fast for a software serial implementation so i just changed it to 9600</p> <pre><code> sim800l.begin(9600); //Begin serial communication with Arduino and SIM800L </code></pre> <p>good luck from the past :)</p>
93785
|arduino-uno|sensors|stepper|stepper-motor|
TMC2208 Stepper Motor does not change its RPM linearly
2023-07-12T14:46:52.257
<p>This is my first project working with stepper motors, so I may have a bit of a shaky understanding of the electronic side of the project. I'm trying to create a simple device with 4 buttons connected to a stepper motor driver/NEMA 17 motor, with the ability to increase/decrease RPM, switch motor spin direction, and run the motor with the button being held down. (LCD screen included for output as well)</p> <p>I'm noticing that when changing the RPM on my motor, i.e. from 3.2 to 3.1 to 3.0, the speed of the motor is really slow, then when set to 3.0, suddenly increases a lot, but goes down when setting the RPM back down to 2.8 or so. This occurs multiple times along different intervals of RPMs that I have tested as well.</p> <p>I think that there may be an issue with the method with which I am calculating the pulse delay given the RPM in my function <code>setRPM()</code> at the end of my code or with the way that I am micro-stepping, which I am doing because I need extremely precise movement.</p> <p>Included below is the code that I used to run with my TMC2208 driver. (Sorry if it is rather long, but I included comments to document my thought process when programming the Arduino.)</p> <p>Included list of RPMs and pulse delays</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th style="text-align: center;">rpm</th> <th style="text-align: center;">pulse_delay (us)</th> </tr> </thead> <tbody> <tr> <td style="text-align: center;">1</td> <td style="text-align: center;">37500 (too fast)</td> </tr> <tr> <td style="text-align: center;">2</td> <td style="text-align: center;">18750 (too fast)</td> </tr> <tr> <td style="text-align: center;">2.25</td> <td style="text-align: center;">16666.6667 (works)</td> </tr> <tr> <td style="text-align: center;">2.5</td> <td style="text-align: center;">15000 (works)</td> </tr> <tr> <td style="text-align: center;">3</td> <td style="text-align: center;">12500 (works)</td> </tr> <tr> <td style="text-align: center;">5</td> <td style="text-align: center;">7500 (works)</td> </tr> <tr> <td style="text-align: center;">10</td> <td style="text-align: center;">3759 (works)</td> </tr> </tbody> </table> </div> <pre class="lang-c prettyprint-override"><code>// Stepper motor run code with TMC2208 driver and LCD code #include &lt;LiquidCrystal_I2C.h&gt; #include &lt;Wire.h&gt; #include &lt;Stepper.h&gt; // Define Pins for Step Motor Driver #define stepPin 7 // define pin for step #define dirPin 8 // define pin for direction #define enPin 9 // define pin for enable ^^ Do I need this? // Define Buttons for Speed and Direction #define buttGo 10 // define pin for button input #define buttSwitch 11 // define pin for button input #define incSpeed 12 // define button for increasing speed #define decSpeed 13 // define button for decreeasing speed // Define LCD pinout const int en = 2, rw = 1, rs = 0, d4 = 4, d5 = 5, d6 = 6, d7 = 7, bl = 3; // Adapter Pinout const int i2c_addr = 0x27; // Adapter pinout LiquidCrystal_I2C lcd(i2c_addr, en, rw, rs, d4, d5, d6, d7, bl, POSITIVE); /* Formulas for determining RPM Assuming one step per pulse, delay is: wait = (μs/min)*(1/rpm)*(1/pulses per revolution) - overhead Overhead = extra time it takes to run digitalWrite twice and loop RPM = (steps per second)/(steps per revolution) * (60 seconds/minute) step angle = 1.8 degrees ; 200 steps per revolution ; .005 revolutions per step Solving for Steps Per Second: SPS = (RPM)/((REV_P_STEP)*(60 sec/min)) According to Notes: C0 = 15 * M_PI ; Motor X Circumference XSPR = 1 * (200 * 11) ; Motor X Steps per Rotation dVx = dS * (XSPR/C0) ; Desired X-Axis time from mm/s to x-axis steps/sec (dS represents desired x-axis speed) Assuming we use a button/knob, each increment/decrement would change the mm/s by 0.1 So, to get the necessary pulse delay, increment/decrement by: dVx = 0.1 * (1 * (200 * 11))/(15*M_PI) Example: If we have an initial target rpm of 10, that gives us a dS of 10 As such, dVx which is our speed in steps will be 10 * (1 * (200 * 11)) / (15 * M_PI) All of these variables are set globally wait = (microsecondsPminute)*(1/RPM)*(1/pulsesPrevolution) - overhead rpm / 60 = rps 60 / rpm = spr (60 / rpm)/360 = spd ((60 / rpm)/360) * 1.8 = sps *** Frequency = (RPM)/((Resolution/360)*60) Resolution = 360/(Steps/Revolution) For us, Resolution = 360/(200); so Resolution = 1.8** Frequency = (RPM)/(0.005 * 60) = RPM/(0.3) * T_inc = incremental torque produced with each microstep T_hfs = holding torque (full-step operation) SDR = step division ratio (number of microsteps per full step) T_inc = T_hfs * sin(90/SDR) T_inc = 0.14 * sin(90/256) T_inc = 0.00085902385 */ float resolution = 1.8; float rpm = 10; float pulse_delay; // Temporary starting value that will change after void setup bool buttonState = false; bool onState = false; // Set up output types void setup() { Serial.begin(9600); // Change this baud rate to whatever rate the LCD screen runs on - should generally be 9600 // Set up LCD screen pulse_delay = setRPM(rpm, resolution); lcd.begin(16, 2); // set up the LCD's number of columns and rows: lcd.setCursor(0, 0); lcd.print(&quot;Current RPM: &quot;); lcd.setCursor(12, 0); lcd.print(rpm); lcd.setCursor(0, 1); lcd.print(&quot;MOVE RIGHT&quot;); // Sets up buttons pinMode(buttSwitch, INPUT); pinMode(buttGo, INPUT); pinMode(incSpeed, INPUT); pinMode(decSpeed, INPUT); // Establish initials pinMode(enPin, OUTPUT); digitalWrite(enPin, HIGH); // deactivate driver pinMode(dirPin, OUTPUT); digitalWrite(dirPin, HIGH); pinMode(stepPin, OUTPUT); digitalWrite(enPin, LOW); // activates driver } // Revolutions per second should be able specified to the tenths // Run code to continual void loop() { // Read Buttons Being Pressed int pressSwitch = digitalRead(buttSwitch); int pressGo = digitalRead(buttGo); int pressInc = digitalRead(incSpeed); int pressDec = digitalRead(decSpeed); pulse_delay = setRPM(rpm, resolution); //pulse_delay = (rpm * 200)/60; if (pressSwitch == HIGH) // Moves motor Right (Counter-Clockwise) { if (buttonState == 0) { digitalWrite(dirPin, LOW); // sets direction of the motor turning buttonState = 1; lcd.setCursor(0, 1); lcd.print(&quot;MOVE LEFT&quot;); delay(500); } else { if (buttonState == 1) { digitalWrite(dirPin, HIGH); // sets direction of the motor turning buttonState = 0; lcd.setCursor(0, 1); lcd.print(&quot;MOVE RIGHT&quot;); delay(500); } } } if (pressGo == HIGH) // Moves motor { digitalWrite(stepPin, HIGH); // This LOW to HIGH change is what creates the &quot;Rising Edge&quot; so the easydriver knows when to step. delayMicroseconds(pulse_delay); digitalWrite(stepPin, LOW); } if (pressInc == HIGH) // Increases RPM { rpm = rpm + 0.1; delay(150); lcd.setCursor(12, 0); lcd.print(rpm); } if (pressDec == HIGH) // Decreases RPM { rpm = rpm - 0.1; delay(150); lcd.setCursor(12, 0); lcd.print(rpm); } } // Function to get pulse delay time based off of inputted RPM value float setRPM(float rpm, float resolution) { /* float temper = ((60 / rpm) / 360); float pulsetime = ((temper * resolution) * 1000000); 1 rpm = 37500 us delay (too fast) 2 rpm = 18750 us delay (too fast) 2.25 rpm = 16666.6667 us delay 2.5 rpm = 15000 us delay 3 rpm = 12500 us delay 5 rpm = 7500 us delay 10 rpm = 3750 us delay */ unsigned int pulsetime = (60000000 / (1600 * rpm)); return pulsetime; // Converts to microseconds } </code></pre>
<p>For reference for any future readers who have had similar problems using a TMC2208 Stepper Motor - I have attached my annotated code to this answer for your use. In the annotation, I also include equations that can be used to determine spacings for a coiling setup.</p> <pre><code>// Stepper motor run code with A4988 driver and LCD code #include &lt;LiquidCrystal_I2C.h&gt; #include &lt;Wire.h&gt; #include &lt;Stepper.h&gt; // Define Pins for Step Motor Driver #define stepPin 7 // define pin for step #define dirPin 8 // define pin for direction #define enPin 9 // define pin for enable ^^ Do I need this? // Define Buttons for Speed and Direction #define buttGo 10 // define pin for button input #define buttSwitch 11 // define pin for button input #define incSpeed 12 // define button for increasing speed #define decSpeed 13 // define button for decreeasing speed // Define LCD pinout const int en = 2, rw = 1, rs = 0, d4 = 4, d5 = 5, d6 = 6, d7 = 7, bl = 3; // Adapter Pinout const int i2c_addr = 0x27; // Adapter Pinout LiquidCrystal_I2C lcd(i2c_addr, en, rw, rs, d4, d5, d6, d7, bl, POSITIVE); /* Formulas for determining RPM Assuming one step per pulse, delay is: wait = (μs/min)*(1/rpm)*(1/pulses per revolution) - overhead Overhead = extra time it takes to run digitalWrite twice and loop RPM = (steps per second)/(steps per revolution) * (60 seconds/minute) step angle = 1.8 degrees ; 200 steps per revolution ; .005 revolutions per step Solving for Steps Per Second: SPS = (RPM)/((REV_P_STEP)*(60 sec/min)) According to John Craig: C0 = 15 * M_PI ; Motor X Circumference XSPR = 1 * (200 * 11) ; Motor X Steps per Rotation dVx = dS * (XSPR/C0) ; Desired X-Axis time from mm/s to x-axis steps/sec (dS represents desired x-axis speed) Assuming we use a button/knob, each increment/decrement would change the mm/s by 0.1 So, to get the necessary pulse delay, increment/decrement by: dVx = 0.1 * (1 * (200 * 11))/(15*M_PI) Example: If we have an initial target rpm of 10, that gives us a dS of 10 As such, dVx which is our speed in steps will be 10 * (1 * (200 * 11)) / (15 * M_PI) All of these variables are set globally wait = (microsecondsPminute)*(1/RPM)*(1/pulsesPrevolution) - overhead rpm / 60 = rps 60 / rpm = spr (60 / rpm)/360 = spd ((60 / rpm)/360) * 1.8 = sps *** *Assume from measured diameter with calipers that it is 12 mm (Check 11.85 as well) To get Spacings: V_extruder / RPM_rod V_extruder = M_PI * Diam_extruder * RPM_extruder (in (mm*rev)/min) RPM_rod = 13 rpm (set from original bought parts) V_extruder = M_PI * 12 mm * X Spacing = (M_PI * 12 * X) / 9.64507699 RPM Spacing = 3.90863773 * X For Spacings of 3 mm... 0.76753084 rev/min ~= 0.77 rev/min For Spacings of 5 mm... 1.27921807 rev/min ~= 1.28 rev/min For Spacings of 7 mm... 1.79090529 rev/min ~= 1.79 rev/min * y = 1.0715x + 2.6653 y = Voltage Setting x = RPM For Voltage Setting of 13, RPM = 9.64507699 T_inc = incremental torque produced with each microstep T_hfs = holding torque (full-step operation) SDR = step division ratio (number of microsteps per full step) T_inc = T_hfs * sin(90/SDR) T_inc = 0.14 * sin(90/256) T_inc = 0.00085902385 */ float resolution = 1.8; float rpm = 3; unsigned int pulse_delay; // Temporary starting value that will change after void setup bool buttonState = false; bool onState = false; // Set up output types void setup() { Serial.begin(9600); // Change this baud rate to whatever rate the LCD screen runs on - should generally be 9600 // Set up LCD screen pulse_delay = setRPM(rpm); lcd.begin(16, 2); // set up the LCD's number of columns and rows: lcd.setCursor(0, 0); lcd.print(&quot;Current RPM: &quot;); lcd.setCursor(12, 0); lcd.print(rpm); lcd.setCursor(0, 1); lcd.print(&quot;MOVE RIGHT&quot;); // Sets up buttons pinMode(buttSwitch, INPUT); pinMode(buttGo, INPUT); pinMode(incSpeed, INPUT); pinMode(decSpeed, INPUT); // Establish initials pinMode(enPin, OUTPUT); digitalWrite(enPin, HIGH); // deactivate driver pinMode(dirPin, OUTPUT); digitalWrite(dirPin, HIGH); pinMode(stepPin, OUTPUT); digitalWrite(enPin, LOW); // activates driver } // Revolutions per second should be able specified to the tenths // Run code to continual void loop() { // Read Buttons Being Pressed int pressSwitch = digitalRead(buttSwitch); int pressGo = digitalRead(buttGo); int pressInc = digitalRead(incSpeed); int pressDec = digitalRead(decSpeed); pulse_delay = setRPM(rpm); //pulse_delay = (rpm * 200)/60; if (pressSwitch == HIGH) // Moves motor Right (Counter-Clockwise) { if (buttonState == 0) { digitalWrite(dirPin, LOW); // sets direction of the motor turning buttonState = 1; lcd.setCursor(0, 1); lcd.print(&quot;MOVING LEFT&quot;); delay(500); } else { if (buttonState == 1) { digitalWrite(dirPin, HIGH); // sets direction of the motor turning buttonState = 0; lcd.setCursor(0, 1); lcd.print(&quot;MOVING RIGHT&quot;); delay(500); } } } // Both of the next functions move the motor, but switches between Microseconds and Milliseconds in delay time to fit. if (pressGo == HIGH &amp;&amp; pulse_delay &gt;= 16383) // Moves motor { digitalWrite(stepPin, HIGH); // This LOW to HIGH change is what creates the &quot;Rising Edge&quot; so the easydriver knows when to step. delay(pulse_delay/1000); digitalWrite(stepPin, LOW); } if (pressGo == HIGH &amp;&amp; pulse_delay &lt; 16383) { digitalWrite(stepPin, HIGH); // This LOW to HIGH change is what creates the &quot;Rising Edge&quot; so the easydriver knows when to step. delayMicroseconds(pulse_delay); digitalWrite(stepPin, LOW); } if (pressInc == HIGH) // Increases RPM { rpm = rpm + 0.01; delay(150); lcd.setCursor(12, 0); lcd.print(rpm); } if (pressDec == HIGH) // Decreases RPM { rpm = rpm - 0.01; delay(150); lcd.setCursor(12, 0); lcd.print(rpm); } } // Function to get pulse delay time based off of inputted RPM value float setRPM(float rpm) { /* float temper = ((60 / rpm) / 360); float pulsetime = ((temper * resolution) * 1000000); 1 rpm = 37500 us delay (too fast) 2 rpm = 18750 us delay (too fast) 2.25 rpm = 16666.6667 us delay 2.5 rpm = 15000 us delay 3 rpm = 12500 us delay 5 rpm = 7500 us delay 10 rpm = 3750 us delay */ unsigned int pulsetime = (60000000 / (1600 * rpm)); return pulsetime; // Converts to microseconds } </code></pre>
93789
|sd-card|
How to estimate the storage room for txt file when writing data to SD card module?
2023-07-12T16:53:03.447
<p>I'm planning to use Arduino UNO to do some measurements and record it in a SD card module. The measurements is going to last for a year or 20 month. I need some advice on how to estimate how long can the SD card storage last without overflow. Right now I'm doing measurements every second, each second contains 13 lines of data, each line is roughly 30 characters. How big is the txt file gonna be if I left the Arduino unit recording for a year?</p>
<p>What type of SD card are you using? Based on the capacity, you can calculate SD card storage time to overflow with data/second. Since a character has a size of one byte, the amount of data used per day should be 30 * 13 * 86400 (sec/day) = 33696000 bytes or 0.033696 gb per day.</p>
93798
|c++|library|pins|
Trying to resolve invalid conversion from 'byte' {aka 'unsigned char'} to
2023-07-13T06:32:38.630
<p>I'm trying to use an existing Arduino library on the Raspberry Pi Pico. The library is here:</p> <p><a href="https://github.com/j-bellavance/EdgeDebounce/tree/master" rel="nofollow noreferrer">https://github.com/j-bellavance/EdgeDebounce/tree/master</a></p> <p>It's based on some interesting insight at Jack Ganssel's blog: <a href="http://www.ganssle.com/debouncing.htm" rel="nofollow noreferrer">http://www.ganssle.com/debouncing.htm</a></p> <p>The library works great on an ATMega 328, but I got two errors when changing to the Raspberry Pi Pico.</p> <p>The first one was resolved by editing the last line of EdgeDebounce.h like this:</p> <pre><code>//#endif; // Arduino ATMega version #endif // Pico version, also works on ATMega </code></pre> <p>The second is a bit more complex. Here's the relevant section of code, these are lines 78 - 102 in EdgeDebounce.cpp :</p> <pre><code> byte EdgeDebounce::debounce(byte pin) { unsigned long pinStatus; do { pinStatus = 0xffffffff; for (byte i = 1; i &lt;= MYsensitivity; i++) pinStatus = (pinStatus &lt;&lt; 1) | digitalRead(pin); } while ((pinStatus != debounceDontCare) &amp;&amp; (pinStatus != 0xffffffff)); return byte(pinStatus &amp; 0x00000001); }//debounce------------------------------------------------------------------------------------------------ //updateStatus=================================================================== //After releasing EdgeDebounceLite, I realized that EdgeDebounce could do more //With this small piece of code, EdgeDebounce can return if a switch is // .isclosed(); //Conducting current // .isopen(); //Not conducting current // .rose(); //Just went from open to closed // .fell(); //just went from closed to open //------------------------------------------------------------------------------- void EdgeDebounce::update() { byte newStatus = debounce(); if (MYmode == PULLUP) newStatus = !newStatus; if (MYstatus == OPEN &amp;&amp; newStatus == CLOSED) MYrose = true; else MYrose = false; if (MYstatus == CLOSED &amp;&amp; newStatus == OPEN) MYfell = true; else MYfell = false; MYstatus = newStatus; }//update------------------------------------------------------------------------- </code></pre> <p>When I try to compile, I get this error:</p> <pre><code>c:\Users\thisuser\Documents\Arduino\libraries\EdgeDebounce\EdgeDebounce.cpp: In member function 'void EdgeDebounce::update()': c:\Users\thisuser\Documents\Arduino\libraries\EdgeDebounce\EdgeDebounce.cpp:102:14: error: invalid conversion from 'byte' {aka 'unsigned char'} to 'pinStatus' [-fpermissive] 102 | MYstatus = newStatus; | ^~~~~~~~~ | | | byte {aka unsigned char} exit status 1 Compilation error: exit status 1 </code></pre> <p>So I see that the byte of &quot;newStatus&quot; doesn't convert to &quot;pinStatus&quot; which is an unsigned long. I've done a bunch of Google searches but can't quite figure out what the fix is.</p>
<p>In C and in much pre-standard C++ nothing stops you just assigning an integer value to a variable of enumeration type. In standard C++ (from 1998 onward) that requires an explicit type conversion (a &quot;cast&quot;).</p> <p>The <a href="https://github.com/arduino/ArduinoCore-avr/blob/1.8.6/platform.txt#L28" rel="nofollow noreferrer">AVR Arduino core supplies</a> the <code>-fpermissive</code> option to the compiler which among other things allows the implicit conversion they're doing despite not being standards compliant C++. Whatever you're using (odds are <a href="https://github.com/earlephilhower/arduino-pico/blob/3.3.0/platform.txt" rel="nofollow noreferrer">this</a> or <a href="https://github.com/arduino/ArduinoCore-mbed/blob/4.0.2/platform.txt" rel="nofollow noreferrer">this</a>) for RPI Pico Arduino core does not provide the <code>-fpermissive</code> option. A lot of Arduino cores don't and probably shouldn't.</p> <p>You <em>could</em> modify the RPI Pico core's platform.txt to give the <code>-fpermissive</code> option to g++, but it is probably better to make the code compliant.</p> <h2>Minimal change</h2> <p>There are probably dozens of ways to do this, but a combination of <em>mimimal</em> and <em>pleasing</em> to C++ nerds probably looks like:</p> <pre class="lang-cpp prettyprint-override"><code>MYstatus = static_cast&lt;pinStatus&gt;(newStatus); </code></pre> <h3>Alternative Casts</h3> <pre class="lang-cpp prettyprint-override"><code>MYstatus = static_cast&lt;decltype(MYstatus)&gt;(newStatus); // fancier MYstatus = (pinStatus)newStatus; // traditional cast MYstatus = pinStatus(newStatus); // function-style cast MYstatus = (decltype(MYstatus))newStatus; // uhhh MYstatus = (decltype(MYstatus))(newStatus); // sure... why not? </code></pre> <p>The <code>static_cast</code> declares in intent in a way that other types of cast don't. <code>decltype</code> would make that line survive changes to the type of MYstatus better, but <code>decltype</code> is not as widely understood.</p> <h3>Alternately not type-converting at all</h3> <p>You can also observe that <code>return byte(pinStatus &amp; 0x00000001);</code> is the <a href="https://github.com/j-bellavance/EdgeDebounce/blob/ff33c6/EdgeDebounce.cpp#L84" rel="nofollow noreferrer">only point of return</a> from <code>byte EdgeDebounce::debounce(byte pin)</code>. So you know this function returns either 0 (false) or 1 (truthy). That's just what's going to happen with applying <code>&amp; 1</code>.</p> <p>They've <a href="https://github.com/j-bellavance/EdgeDebounce/blob/ff33c6/EdgeDebounce.h#L34" rel="nofollow noreferrer">defined the enumeration type</a>:</p> <pre><code>enum pinStatus {OPEN, CLOSED}; </code></pre> <p>The rules of C and C++ (even pre-standard C++) will assign these constants numeric values 0 and 1, where they weren't explicitly given values and were listed in that order.</p> <p>So, you could replace <code>MYstatus = newStatus;</code> with:</p> <pre class="lang-cpp prettyprint-override"><code>{ if (newStatus) { MYstatus = CLOSED; } else { MYstatus = OPEN; } } </code></pre> <p>Or use the ternary operator if you want don't mind people trying to argue with you:</p> <pre class="lang-cpp prettyprint-override"><code>MYstatus = newStatus ? CLOSED : OPEN; </code></pre>
93803
|arduino-uno|serial|
Why this simple serial monitor code not working?
2023-07-13T10:47:05.017
<p>The follwoing code echoes whatever arduino recieves through reciever pin. The idea is that arduino will echo whole data in the buffer on the same line and starting from the new line while echoing the next data recieved in the buffer.</p> <pre><code>void setup() { Serial.begin(9600); } void loop() { if(Serial.available()) { int count = Serial.available(); for(int i = 0; i &lt; count; i++) { char character = Serial.read(); Serial.print(character); } Serial.print(&quot;\n&quot;); } } </code></pre> <p>When I run the code it prints the characters line by line. for example if I enter the word &quot;QUICK&quot; it echoes the following</p> <pre><code>Q U I C K </code></pre> <p>Whereas I think it should be echoing</p> <pre><code>QUICK </code></pre> <p>Please help me out.</p>
<p>You seem to have the assumption, that the string &quot;QUICK&quot; is send as one package of characters, because you send it with one keypress from the Serial Monitor. But Serial (UART) is a &quot;serial&quot; protocol, meaning, that each byte (aka character for ASCII encoding) is send sequentially.</p> <p>At 9600 baud each byte will take about 1ms to transmit. Also: small random delays can be introduced by the PC or in the USB communication (if you are communication through a USB to Serial chip, like when you connect the Uno via USB).</p> <p>Your code runs faster than the data arrives at the Unos microcontroller. The first <code>if</code> clause is entered as soon, as there is one byte in your Serial buffer. Then you start reading the data from the buffer, but at that time no further bytes did arrive. So the loop is exited after one iteration.</p> <p>If you want to process the Serial data line by line, you should send a line ending from the Serial Monitor (or whichever program you are using) via the Line ending option. The common way is to use <code>\n</code> aka the newline character as line ending. Then in your code you should read the data until you receive the newline character.</p> <p>That can be done in multiple ways. One way is to read each arriving character into your own buffer, which is big enough to hold the maximum number of characters, that can occur in your messages. Then, when receiving the newline character you can process the data in the buffer. A variables holds the current position in the buffer:</p> <pre><code>unsigned int pos = 0; char buffer[20] = &quot;&quot;; // enough space for 19 characters + the null character for terminating the string correctly void setup(){ Serial.begin(9600); } void loop(){ if(Serial.available()){ char c = Serial.read(); if(c != '\n'){ buffer[pos] = c; // Adding the received character to the buffer if(pos &lt; sizeof(buffer) - 1){ // incrementing the position variable to point to the next position in the buffer // but only, if there is enough space in the buffer left // otherwise this code will overwrite the last character pos++; } } else { buffer[pos] = 0; // Terminating the string correctly // Process the message here Serial.println(buffer); // Reset buffer by setting the position back to zero pos = 0; } } } </code></pre> <p>Note: This code needs your <code>loop()</code> function to iterate fast enough, so that you won't miss more data, than the internal buffer of Serial can hold (I think 32 characters). So you probably don't want to use long delays (which is nearly always a bad idea anyways, see non-blocking coding and the <code>millis()</code> function).</p>
93807
|arduino-ide|led|nodemcu|button|digitalwrite|
LED doesn't completely turn off with digitalWrite(led, LOW);
2023-07-13T20:20:44.887
<p>When I was testing out a program I found a strange behavior of ESP8266.</p> <p>LEDs don't turn off completely in the first <code>digitalWrite(led, LOW)</code>, just the brightness of the LED goes down, but it does turn off in the second <code>digitalWrite(led, LOW)</code>.</p> <p>I don't know if it's related to the code or the circuit, so here are both (the program is just two different visual patterns of LEDs toggled by a button)</p> <pre><code>#define led1 D0 #define led2 D1 #define led3 D2 #define led4 D3 #define button D7 unsigned long pressedButton; bool change = 0; unsigned long previousTime = millis(); unsigned int difference; void setup() { pinMode(led1, OUTPUT); pinMode(led2, OUTPUT); pinMode(led3, OUTPUT); pinMode(led4, OUTPUT); pinMode(button, INPUT_PULLUP); } void loop(){ if (!digitalRead(button) &amp;&amp; millis()-pressedButton&gt;200){ //check if button was pressed to change visual pattern of leds pressedButton = millis(); change = !change; digitalWrite(led1, LOW); //here led completely turn off digitalWrite(led2, LOW); digitalWrite(led3, LOW); digitalWrite(led4, LOW); previousTime = millis(); } difference = millis()-previousTime; if (!change){ //default visual pattern of leds if (!digitalRead(led1) &amp;&amp; difference&gt;=200){ digitalWrite(led1, HIGH); } if (!digitalRead(led2) &amp;&amp; difference&gt;=400){ digitalWrite(led2, HIGH); } if (!digitalRead(led3) &amp;&amp; difference&gt;=600){ digitalWrite(led3, HIGH); } if (!digitalRead(led4) &amp;&amp; difference&gt;=800){ digitalWrite(led4, HIGH); } if (difference&gt;=1000){ digitalWrite(led4, LOW); //the leds just shrink here } if (difference&gt;=1200){ digitalWrite(led3, LOW); } if (difference&gt;=1400){ digitalWrite(led2, LOW); } if (difference&gt;=1600){ digitalWrite(led1, LOW); previousTime = millis(); } } if (change){ //alternative pattern if (!digitalRead(led1) &amp;&amp; difference&gt;=200 &amp;&amp; change){ digitalWrite(led1, HIGH); digitalWrite(led4, HIGH); digitalWrite(led2, LOW); digitalWrite(led3, LOW); } if (digitalRead(led1) &amp;&amp; difference&gt;=400 &amp;&amp; change){ digitalWrite(led1, LOW); digitalWrite(led4, LOW); digitalWrite(led2, HIGH); digitalWrite(led3, HIGH); previousTime = millis(); } } } </code></pre> <p><a href="https://i.stack.imgur.com/Xf24I.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Xf24I.png" alt="" /></a> Actually, it's a NodeMCU Esp8266, with the pins defined on the code and a 470 ohms resistor. (obs: resistor is not shorted, in my breadboard those rows are separated)</p>
<pre class="lang-c++ prettyprint-override"><code>if (!digitalRead(led3) &amp;&amp; difference&gt;=600){ digitalWrite(led3, HIGH); } if (!digitalRead(led4) &amp;&amp; difference&gt;=800){ digitalWrite(led4, HIGH); } if (difference&gt;=1000){ digitalWrite(led4, LOW); //the leds just shrink here } if (difference&gt;=1200){ digitalWrite(led3, LOW); } </code></pre> <p>Consider what will happen when the difference is &gt;= 1000.</p> <p>If the LED is off you turn it on (because it passes the first test, the difference is &gt;= 600), and a moment later you turn it off. So the LEDs are being turned on and off in quick succession, which makes them look dim.</p> <p>Try re-ordering the tests, and add <code>else</code> for each subsequent one. That seems to work for me:</p> <pre class="lang-c++ prettyprint-override"><code> if (!change){ //default visual pattern of leds if (difference&gt;=1600){ digitalWrite(led1, LOW); previousTime = millis(); } else if (difference&gt;=1400){ digitalWrite(led2, LOW); } else if (difference&gt;=1200){ digitalWrite(led3, LOW); } else if (difference&gt;=1000){ digitalWrite(led4, LOW); } else if (!digitalRead(led4) &amp;&amp; difference&gt;=800){ digitalWrite(led4, HIGH); } else if (!digitalRead(led3) &amp;&amp; difference&gt;=600){ digitalWrite(led3, HIGH); } else if (!digitalRead(led2) &amp;&amp; difference&gt;=400){ digitalWrite(led2, HIGH); } else if (!digitalRead(led1) &amp;&amp; difference&gt;=200){ digitalWrite(led1, HIGH); } } </code></pre> <hr /> <p>Also, that resistor on the bottom row isn't achieving anything because all the pins on the bottom row are connected together so it is just shorted out. Not good for the LEDs or the processor.</p>
93817
|led|analogread|voltage-level|arduino-pro-mini|electronics|
How to turn LEDs based on voltage readings?
2023-07-14T14:27:17.920
<p>I am trying to turn LEDs in an LED bridge based on the voltage reading from a power source. when the Voltage is zero nothing is ON and then the LEDs gradually turn ON as increase the voltage connected to the Ao pin. ( I am using a pro trinket 3V 120 MHZ)</p> <p>This is my code:</p> <pre class="lang-cpp prettyprint-override"><code>const int analogPin = A0; // the pin that the potentiometer is attached to const int ledCount = 7; // the number of LEDs in the bar graph int ledPins[] = { 3, 4, 5, 6, 8, 9, 10}; // an array of pin numbers to which LEDs are attached void setup() { // loop over the pin array and set them all to output: for (int thisLed = 0; thisLed &lt; ledCount; thisLed++) { pinMode(ledPins[thisLed], OUTPUT); } } void loop() { // read the potentiometer: int sensorReading = analogRead(analogPin); // map the result to a range from 0 to the number of LEDs: int ledLevel = map(sensorReading, 0, 1023, 0, ledCount); // loop over the LED array: for (int thisLed = 0; thisLed &lt; ledCount; thisLed++) { // if the array element's index is less than ledLevel, // turn the pin for this element on: if (thisLed &lt; ledLevel) { digitalWrite(ledPins[thisLed], HIGH); } // turn off all pins higher than the ledLevel: else { digitalWrite(ledPins[thisLed], LOW); } } } </code></pre> <p>However, I am not getting the outcome I want. when there is 0 voltage one LED turns ON instead of nothing. when there is a voltage all connected LEDs turn ON regardless of what the voltage is</p> <p>when there is no voltage connected (floating wires), I get this:</p> <p><a href="https://i.stack.imgur.com/0Itc3.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/0Itc3.png" alt="enter image description here" /></a></p> <p>when I put any amount of Voltage as long as the power supply is ON the results is the same:</p> <p><a href="https://i.stack.imgur.com/e99yj.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/e99yj.png" alt="enter image description here" /></a></p> <p>Note: What am I doing wrong? edit: connections are something like that but with fewer digital pins. <a href="https://i.stack.imgur.com/yjNZJ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/yjNZJ.png" alt="enter image description here" /></a></p> <p>Note: What am I doing wrong!EDIT: I was able to get around and print the serial monitor result:</p> <ul> <li>when the power source is OFF, the reading at A0 (sensorreading) is:</li> </ul> <p><a href="https://i.stack.imgur.com/RhxP6.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/RhxP6.png" alt="enter image description here" /></a></p> <p>Note: What am I doing wrong!- when the power source is ON at any value, the reading at A0 (sensorreading) is:</p> <p><a href="https://i.stack.imgur.com/OsuIp.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/OsuIp.png" alt="enter image description here" /></a></p> <p>(Note: What am I doing wrong!)</p>
<p>I can say your code is working but you need to check the wirering of your circuit .</p> <p>Note that the voltage on the analogread pin should not be an oscillating voltage at low frequency like AC voltage. It should be a direct stable voltage to get the correct output.</p> <p>Here is my diagram below for you to make changes with yours . Ive testedit on my simulation app and its working perfectly.</p> <p>The code</p> <pre><code> const int analogPin = A0; // the pin that the potentiometer is attached to const int ledCount = 7; // the number of LEDs in the bar graph int ledPins[] = { 3, 4, 5, 6, 8, 9, 10}; // an array of pin numbers to which LEDs are attached void setup() { Serial.begin(9600); // loop over the pin array and set them all to output: for (int thisLed = 0; thisLed &lt; ledCount; thisLed++) { pinMode(ledPins[thisLed], OUTPUT); } } void loop() { // read the potentiometer: int sensorReading = analogRead(analogPin); Serial.print(&quot;sensor read : &quot;); Serial.println(sensorReading); // map the result to a range from 0 to the number of LEDs: int ledLevel = map(sensorReading, 0, 1023, 0, ledCount); Serial.print(&quot;led Level : &quot;); Serial.println(ledLevel); // loop over the LED array: for (int thisLed = 0; thisLed &lt; ledCount; thisLed++) { // if the array element's index is less than ledLevel, // turn the pin for this element on: if (thisLed &lt; ledLevel) { digitalWrite(ledPins[thisLed], HIGH); } // turn off all pins higher than the ledLevel: else { digitalWrite(ledPins[thisLed], LOW); } } //delay(500); //for debugging } </code></pre> <p>The diagram</p> <p><a href="https://i.stack.imgur.com/Ji1xW.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Ji1xW.png" alt="voltage-follower" /></a></p> <p>Note that if you're tryingto measure a voltage higher than 5 volts, make sure to build the voltage divider circuit with the appropriate resistor values for you to get 5v output as that is the highest volt the arduino can carry. measure Example below shows a 12 volts dc battery voltage measure(note that 5 volts is the highest voltage supplied to the arduino, not the full 12 volts):</p> <p><a href="https://i.stack.imgur.com/zqAKB.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/zqAKB.png" alt="12 volts" /></a></p>
93818
|esp32|gsm|http|
ArduinoHTTPClient POST multipart/form-data from SD card returning 400 Bad Request
2023-07-14T15:32:14.177
<p>I have been having trouble trying to send a small txt file to my server using the following function with TinyGSM. I know I am connected to the internet and reaching the web server, however, I keep receiving a <code>400 Bad Request</code> code. I think something is wrong with my <code>PostHeader</code>, but I have no clue where or what it could be... I know I am connecting to my server as I try a default get and return webpage text...</p> <pre><code>TinyGsm modem(SerialAT); TinyGsmClient client2(modem); HttpClient client(client2, server, port); void fileUpload(String filename){ if(!initSD()){ return; } File dataFile = SD.open(filename.c_str()); Serial.println(&quot;Uploading File...&quot;); if (!client.connect(server, port)) { Serial.println(&quot;Failed connecting to Server&quot;); return; } String fileType = &quot;text/plain&quot;; String content = &quot;--boundary1\r\n&quot;; content += &quot;Content-Disposition: form-data; name=\&quot;fileToUpload\&quot;; filename=&quot;+String(filename)+&quot;\r\n&quot;; // the fileToUpload is the form parameter content += &quot;Content-Type: &quot;+fileType+&quot;\r\n\r\n&quot;; //after this, post the file data. String closingContent = &quot;\r\n--boundary1--&quot;; //Serial.println(content); client.println(String(&quot;POST &quot;) + &quot;/upload.php&quot; +&quot; HTTP/1.1\r\n&quot;); client.println(String(&quot;Host: &quot;) + server + &quot;\r\n&quot;); client.println(&quot;Content-Type: multipart/form-data; boundary=boundary1\r\n&quot;); client.println(&quot;Connection: close\r\n&quot;); client.println(&quot;Content-Length: &quot;+String(content.length()+dataFile.size()+closingContent.length())+&quot;\r\n&quot;); client.println(content); client.println(); if (dataFile) { // start sending file content while (dataFile.available()) { char c = dataFile.read(); client.print(c); } dataFile.close(); } client.println(closingContent); Serial.println(&quot;File Sent.&quot;); // read the status code and body of the response int statusCode = client.responseStatusCode(); String response = client.responseBody(); Serial.print(&quot;Status code: &quot;); Serial.println(statusCode); Serial.print(&quot;Response: &quot;); Serial.println(response); } </code></pre>
<p>There were a couple issues that I finally managed to solve... I was able to get it to work by <em>not</em> using <code>ArduinoHTTPClient</code>. Here is working code for anyone else who stumbles here.</p> <pre><code>TinyGsmClient client(modem); void fileUpload(String filename){ File dataFile = SD.open(filename.c_str()); Serial.println(&quot;Uploading File...&quot;); if (!client.connect(server, port)) { Serial.println(&quot;Failed connecting to Server&quot;); return; } String fileType = &quot;text/plain&quot;; String content = &quot;--boundary1\r\n&quot;; content += &quot;Content-Disposition: form-data; name=\&quot;fileToUpload\&quot;; filename=&quot;+String(filename)+&quot;\r\n&quot;; // the fileToUpload is the form parameter content += &quot;Content-Type: &quot;+fileType+&quot;\r\n\r\n&quot;; //after this, post the file data. String closingContent = &quot;\r\n--boundary1--\r\n&quot;; //Serial.println(content); client.println(String(&quot;POST &quot;) + &quot;/upload.php&quot; +&quot; HTTP/1.1&quot;); // or wherever you need to call/print to. client.println(String(&quot;Host: &quot;) + server); client.println(&quot;Content-Length: &quot;+String(content.length()+dataFile.size()+closingContent.length())); client.println(&quot;Content-Type: multipart/form-data; boundary=boundary1&quot;); client.println(); client.println(content); if (dataFile) { // start sending file content String data = &quot;&quot;; while (dataFile.available()) { char c = dataFile.read(); data += c; //write every line break... if(c == '\n'){ client.write(data.c_str()); data = &quot;&quot;; } } dataFile.close(); } client.print(closingContent); unsigned long timeout = millis(); while (client.connected() &amp;&amp; millis() - timeout &lt; 50000L) { // Print available data while (client.available()) { char c = client.read(); Serial.print(c); timeout = millis(); } } client.stop(); } </code></pre>
93827
|interrupt|avr|
Pin Change Interrupt Flag timing on 1284P
2023-07-15T05:01:29.567
<p>I want to ask about pin change interrupts on a 1284P chip using MightyCore. I have a question about the timing of multiple interrupts on one port. Specifically, if I am servicing a PCINT vector and another pin in the port changes while I am in the ISR, will it generate another interrupt immediately following the one I am servicing?</p> <p>When I read the datasheet I see:</p> <blockquote> <p>Bit 2 – PCIF2: Pin Change Interrupt Flag 2 When a logic change on any PCINT[23:16] pin triggers an interrupt request, PCIF2 will be set. If the I-bit in SREG and the PCIE2 bit in PCICR are set, the MCU will jump to the corresponding Interrupt Vector. The flag is cleared when the interrupt routine is executed. Alternatively, the flag can be cleared by writing '1' to it.</p> </blockquote> <p>When it says that the flag is cleared when the interrupt routine is executed, does that mean when it enters or exits the ISR? If it is at the end, can I clear the flag in the first line of the ISR and allow another pin change to set it again even if it happens before I exit the ISR?</p>
<p>When it is entered. The wording is slightly vague but I think &quot;when the interrupt routine is executed&quot; means the commencement of execution. Otherwise multiple pin-change interrupts could be easily missed, depending on how long you took inside the ISR.</p> <p>I suggest writing a simple test that saves somewhere what the flag is, upon entering the ISR, and check it is cleared already.</p> <hr /> <p>I wrote this test for the Uno (which is the same basic architecture):</p> <pre class="lang-c++ prettyprint-override"><code>volatile bool firstTime = true; volatile byte PCIFR_copy = 0; ISR (PCINT0_vect) { // handle pin change interrupt for D8 to D13 here if (!firstTime) return; firstTime = false; PCIFR_copy = PCIFR; } // end of PCINT0_vect void setup () { pinMode (9, INPUT_PULLUP); Serial.begin (115200); // pin change interrupt (for D9) PCMSK0 |= bit (PCINT1); // want pin 9 PCIFR |= bit (PCIF0); // clear any outstanding interrupts PCICR |= bit (PCIE0); // enable pin change interrupts for D8 to D13 } // end of setup void loop () { Serial.print (&quot;First time is &quot;); Serial.print ((int) firstTime); Serial.print (&quot;, Flag is &quot;); Serial.println ((int) PCIFR_copy); delay (1000); } // end of loop </code></pre> <p>The PCIFR flag was always zero, even after triggering the pin-change interrupt, which shows that it was cleared upon <strong>entering</strong> the ISR.</p> <blockquote> <p>will it generate another interrupt immediately following the one I am servicing?</p> </blockquote> <p>So, based on the above, the answer is yes it will. Upon leaving the ISR one more instruction will be executed and then the next interrupt will be serviced (assuming a higher-priority interrupt doesn't get in first).</p> <hr /> <p>Another way of looking at it is that the pin change will always set that flag. Between instructions the processor would check that flag (and the flags for the other interrupts) and for the highest priority interrupt, if that flag is set, then it would clear that flag and then commencing processing that interrupt. That is really the only logical way it could work.</p> <hr /> <p>Also, it makes more sense from the design of the processor to clear the flag upon entering the ISR. Apart from the problem that interrupts could be missed if it didn't, when it enters the ISR the processor &quot;knows&quot; which interrupt it is servicing, because it would have checked the PCIFx flag, it would have checked the PCIEx flag (to see if the interrupt should be executed) and it would have then changed the program counter to the appropriate address for that interrupt, after pushing the current program counter onto the stack. This would be the logical time to clear that flag while all this information is in the processor's &quot;head&quot; so to speak.</p> <p>At the end of the ISR the code simply executes a RTI (Return from Interrupt) instruction which doesn't have associated with it which interrupt it is returning from. Thus it would be hard to clear the flag at that point.</p>
93840
|progmem|platformio|
PlatformIO and const PROGMEM
2023-07-16T18:44:34.947
<p>I'm using the DuinoWitchery LCD library (<a href="https://github.com/duinoWitchery/hd44780" rel="nofollow noreferrer">https://github.com/duinoWitchery/hd44780</a>) in a PlatformIO Arduino project with CLion.</p> <p>The following code works if I stick it in main.cpp:</p> <pre><code>// near top of class... const PROGMEM uint8_t decimalDigit[10][8] = { {0x07, 0x05, 0x05, 0x05, 0x07, 0x18, 0x18}, // .0 {0x02, 0x02, 0x02, 0x02, 0x02, 0x18, 0x18}, // .1 {0x07, 0x01, 0x07, 0x04, 0x07, 0x18, 0x18}, // .2 {0x07, 0x01, 0x07, 0x01, 0x07, 0x18, 0x18}, // .3 {0x5, 0x05, 0x07, 0x01, 0x01, 0x18, 0x18}, // .4 {0x07, 0x04, 0x06, 0x01, 0x06, 0x00, 0x18, 0x18}, // .5 {4, 4, 7, 5, 7, 0, 0x18, 0x18}, // .6 {7, 1, 1, 1, 1, 0, 0x18, 0x18}, // .7 {7, 5, 7, 5, 7, 0, 0x18, 0x18}, // .8 {7, 5, 7, 1, 1, 0, 0x18, 0x18}, // .9 }; hd44780_I2Cexp lcd(0x27); // ... snip ... void setup() { for (int x=0; x&lt;8; x++) lcd.createChar((uint8_t)x, decimalDigit[x]); // ...snip... } </code></pre> <p>... but if I move the code into another class, like:</p> <p><strong>Renderer.h</strong></p> <pre><code>class Renderer : BaseRenderer { public: virtual void renderTo(hd44780* lcd) override; // ... snip ... private: const PROGMEM uint8_t decimalDigit[10][8] = { {0x07, 0x05, 0x05, 0x05, 0x07, 0x18, 0x18}, // .0 {0x02, 0x02, 0x02, 0x02, 0x02, 0x18, 0x18}, // .1 {0x07, 0x01, 0x07, 0x04, 0x07, 0x18, 0x18}, // .2 {0x07, 0x01, 0x07, 0x01, 0x07, 0x18, 0x18}, // .3 {0x5, 0x05, 0x07, 0x01, 0x01, 0x18, 0x18}, // .4 {0x07, 0x04, 0x06, 0x01, 0x06, 0x00, 0x18, 0x18}, // .5 {4, 4, 7, 5, 7, 0, 0x18, 0x18}, // .6 {7, 1, 1, 1, 1, 0, 0x18, 0x18}, // .7 {7, 5, 7, 5, 7, 0, 0x18, 0x18}, // .8 {7, 5, 7, 1, 1, 0, 0x18, 0x18}, // .9 }; } </code></pre> <p><strong>Renderer.cpp</strong></p> <pre><code>void Renderer::renderTo(hd44780lcd* lcd) { for (int x=0; x&lt;8; x++) lcd-&gt;createChar((uint8_t)x, decimalDigit[x]); // ...snip... } </code></pre> <p>... the custom characters end up with garbage data.</p> <p>I <strong>think</strong> I might be breaking some esoteric rule that governs where you're allowed to put a <code>const PROGMEM uint8_t[]</code>, and causing the array declared in Renderer.h to end up in SRAM. But I'm not sure how to confirm it OR fix it.</p> <hr /> <p>note: the for/next loop to create the chars is just for the sake of illustration &amp; to demonstrate that something that works in main.setup() fails in Renderer.renderTo(). In <em>real</em> life, the sequence of characters getting rendered to the LCD owns one of the 8 custom characters &amp; redefines it as necessary to be the decimal point and tenths value.</p>
<p>The <code>PROGMEM</code> qualifier can only be applied to statically-allocated constant data. When you move the <code>decimalDigit</code> array inside the class, it becomes a data member, i.e. you have one copy of the array per instance... in RAM. In this case, <code>PROGMEM</code> does not work. My compiler says:</p> <pre><code>warning: ‘__progmem__’ attribute ignored [-Wattributes] </code></pre> <p>If you want to keep the array inside the class, it must be given the <code>static</code> qualifier. It then becomes statically-allocated class data (not instance data):</p> <pre class="lang-cpp prettyprint-override"><code>// Renderer.h: class Renderer : BaseRenderer { public: virtual void renderTo(hd44780* lcd) override; // ... snip ... private: static const PROGMEM uint8_t decimalDigit[10][8]; }; // Renderer.cpp: const PROGMEM uint8_t Renderer::decimalDigit[10][8] = { {0x07, 0x05, 0x05, 0x05, 0x07, 0x18, 0x18}, // .0 {0x02, 0x02, 0x02, 0x02, 0x02, 0x18, 0x18}, // .1 // ... snip ... }; </code></pre> <p>Of course, putting the array within the class is not an obligation. If it is going to be private anyway, the outside world (the files that include Renderer.h) does not need to know about its existence.</p>
93844
|arduino-ide|esp32|espressif|
MD5 of File doesnot match data in flash Error with ESP32 S3
2023-07-17T07:33:15.763
<p>I am getting the <code>fatal error MD5 of file not match data in flash</code>. Below is the output of upload.</p> <pre><code>[1/5] cmd.exe /C &quot;cd /D D:\Users\INOMETRICS\espressif\workspace\blink\build\esp-idf\esptool_py &amp;&amp; python D:/Espressif/frameworks/esp-idf-v4.4/components/partition_table/check_sizes.py --offset 0x8000 partition --type app D:/Users/INOMETRICS/espressif/workspace/blink/build/partition_table/partition-table.bin D:/Users/INOMETRICS/espressif/workspace/blink/build/blink.bin&quot; blink.bin binary size 0x31340 bytes. Smallest app partition is 0x100000 bytes. 0xcecc0 bytes (81%) free. [2/5] Performing build step for 'bootloader' [1/1] cmd.exe /C &quot;cd /D D:\Users\INOMETRICS\espressif\workspace\blink\build\bootloader\esp-idf\esptool_py &amp;&amp; python D:/Espressif/frameworks/esp-idf-v4.4/components/partition_table/check_sizes.py --offset 0x8000 bootloader 0x0 D:/Users/INOMETRICS/espressif/workspace/blink/build/bootloader/bootloader.bin&quot; Bootloader binary size 0x5180 bytes. 0x2e80 bytes (36%) free. [2/3] cmd.exe /C &quot;cd /D D:\Espressif\frameworks\esp-idf-v4.4\components\esptool_py &amp;&amp; D:\Espressif\tools\cmake\3.20.3\bin\cmake.exe -D IDF_PATH=&quot;D:/Espressif/frameworks/esp-idf-v4.4&quot; -D SERIAL_TOOL=&quot;python D:/Espressif/frameworks/esp-idf-v4.4/components/esptool_py/esptool/esptool.py --chip esp32s3&quot; -D SERIAL_TOOL_ARGS=&quot;--before=default_reset --after=hard_reset write_flash @flash_args&quot; -D WORKING_DIRECTORY=&quot;D:/Users/INOMETRICS/espressif/workspace/blink/build&quot; -P D:/Espressif/frameworks/esp-idf-v4.4/components/esptool_py/run_serial_tool.cmake&quot; esptool.py esp32s3 -p COM8 -b 460800 --before=default_reset --after=hard_reset write_flash --flash_mode dio --flash_freq 80m --flash_size 2MB 0x0 bootloader/bootloader.bin 0x10000 blink.bin 0x8000 partition_table/partition-table.bin esptool.py v3.2-dev Serial port COM8 Connecting... Chip is ESP32-S3 Features: WiFi, BLE Crystal is 40MHz MAC: 70:04:1d:be:ab:74 Uploading stub... Running stub... Stub running... Changing baud rate to 460800 Changed. Configuring flash size... Flash will be erased from 0x00000000 to 0x00005fff... Flash will be erased from 0x00010000 to 0x00041fff... Flash will be erased from 0x00008000 to 0x00008fff... Compressed 20864 bytes to 13002... Writing at 0x00000000... (100 %) Wrote 20864 bytes (13002 compressed) at 0x00000000 in 0.1 seconds (effective 1284.4 kbit/s)... File md5: 1d4bc050825217f8434a2cfd167894cd Flash md5: 1b32e380d00eb036ce18a632dedbe04d MD5 of 0xFF is b145c0e952abec491d69c8c5f8ac47c4 A fatal error occurred: MD5 of file does not match data in flash! CMake Error at run_serial_tool.cmake:56 (message): python D:/Espressif/frameworks/esp-idf-v4.4/components/esptool_py/esptool/esptool.py --chip esp32s3 failed </code></pre> <p>I am getting the same error while uploading with esp-idf and Arduino ide or platformio.</p> <p>How could i solve the issue.</p> <p>Regards</p>
<p>Yes, I have managed to get it working now, the issue encountered was with the strapping pins. Specifically, Pin 45 of ESP32S3 is responsible for configuring VDD_SPI_FLASH. To ensure it operates at 3.3V, the pin should be connected to the ground. Otherwise, it will function at 1.8V, which might cause problems with the Flash functionality.</p> <p>Fortunately, this can also be resolved by burning some EFUSES using the espefuse.py tool, which comes along with esptool.py. All you need to do is run the command: <code>espefuse.py set_flash_voltage &lt;voltage&gt;</code> (where voltage can be either 3.3V or 1.8V or OFF). For more details, you can visit: <a href="https://docs.espressif.com/projects/esptool/en/latest/esp32s3/espefuse/set-flash-voltage-cmd.html" rel="nofollow noreferrer">link to the official documentation</a>.</p>
93846
|arduino-uno|esp8266|web-server|esp8266webserver|dht11|
ERROR: return reinterpret_cast<T>(pgm_read_ptr(p));
2023-07-17T09:55:15.790
<p>I need to update <strong>DHT</strong> sensor data to the webserver in <em><strong>JSON</strong></em> format using <strong>ESP8266</strong>. This is my code.</p> <pre class="lang-cpp prettyprint-override"><code>#include &lt;ESP8266WiFi.h&gt; #include &lt;WiFiClient.h&gt; #include &lt;ESP8266WebServer.h&gt; #include &lt;DHT.h&gt; #include &lt;ArduinoJson.h&gt; const char* ssid = &quot;YOUR_SSID&quot;; const char* password = &quot;YOUR PASSWORD&quot;; const int dhtPin = D4; DHT dht(dhtPin, DHT11); ESP8266WebServer server(80); void handleRoot() { float temperature = dht.readTemperature(); float humidity = dht.readHumidity(); if (isnan(temperature) || isnan(humidity)) { server.send(500, &quot;text/plain&quot;, &quot;Failed to read from DHT sensor&quot;); return; } StaticJsonDocument&lt;200&gt; jsonDoc; jsonDoc[&quot;temperature&quot;] = temperature; jsonDoc[&quot;humidity&quot;] = humidity; String jsonString; serializeJson(jsonDoc, jsonString); server.send(200, &quot;application/json&quot;, jsonString); } void setup() { Serial.begin(115200); WiFi.begin(ssid, password); while (WiFi.status() != WL_CONNECTED) { delay(1000); Serial.println(&quot;Connecting to WiFi...&quot;); } Serial.println(&quot;Connected to WiFi&quot;); dht.begin(); server.on(&quot;/&quot;, handleRoot); server.begin(); Serial.println(&quot;Server started&quot;); } void loop() { server.handleClient(); } </code></pre> <p>But I got error like,</p> <pre><code>In file included from c:\Users\Kuralmozhi.R\Documents\Arduino\libraries\ArduinoJson\src/ArduinoJson/Polyfills/static_array.hpp:11:0, from c:\Users\Kuralmozhi.R\Documents\Arduino\libraries\ArduinoJson\src/ArduinoJson/Numbers/FloatTraits.hpp:14, from c:\Users\Kuralmozhi.R\Documents\Arduino\libraries\ArduinoJson\src/ArduinoJson/Numbers/FloatParts.hpp:8, from c:\Users\Kuralmozhi.R\Documents\Arduino\libraries\ArduinoJson\src/ArduinoJson/Json/TextFormatter.hpp:11, from c:\Users\Kuralmozhi.R\Documents\Arduino\libraries\ArduinoJson\src/ArduinoJson/Json/JsonSerializer.hpp:7, from c:\Users\Kuralmozhi.R\Documents\Arduino\libraries\ArduinoJson\src/ArduinoJson/Variant/ConverterImpl.hpp:7, from c:\Users\Kuralmozhi.R\Documents\Arduino\libraries\ArduinoJson\src/ArduinoJson.hpp:37, from c:\Users\Kuralmozhi.R\Documents\Arduino\libraries\ArduinoJson\src/ArduinoJson.h:9, from C:\Users\Kuralmozhi.R\Downloads\ID_2\ID_2.ino:5: c:\Users\Kuralmozhi.R\Documents\Arduino\libraries\ArduinoJson\src/ArduinoJson/Polyfills/pgmspace_generic.hpp: In instantiation of 'typename ArduinoJson6193_F1::enable_if&lt;ArduinoJson6193_F1::is_pointer&lt;T&gt;::value, T&gt;::type ArduinoJson6193_F1::pgm_read(const void*) [with T = const __FlashStringHelper*; typename ArduinoJson6193_F1::enable_if&lt;ArduinoJson6193_F1::is_pointer&lt;T&gt;::value, T&gt;::type = const __FlashStringHelper*]': c:\Users\Kuralmozhi.R\Documents\Arduino\libraries\ArduinoJson\src/ArduinoJson/Deserialization/DeserializationError.hpp:85:12: required from here c:\Users\Kuralmozhi.R\Documents\Arduino\libraries\ArduinoJson\src/ArduinoJson/Polyfills/pgmspace_generic.hpp:15:45: error: 'const void*' is not a pointer-to-object type return reinterpret_cast&lt;T&gt;(pgm_read_ptr(p)); ^ exit status 1 Compilation error: exit status 1 </code></pre> <p>I don't know how to solve this error. Please suggest me some ideas!</p> <hr /> <p>I tried to update ESP8266. But now it shows like this,</p> <pre><code>Variables and constants in RAM (global, static), used 28984 / 80192 bytes (36%) ║ SEGMENT BYTES DESCRIPTION ╠══ DATA 1504 initialized variables ╠══ RODATA 1376 constants ╚══ BSS 26104 zeroed variables Instruction RAM (IRAM_ATTR, ICACHE_RAM_ATTR), used 60439 / 65536 bytes (92%) ║ SEGMENT BYTES DESCRIPTION ╠══ ICACHE 32768 reserved space for flash instruction cache ╚══ IRAM 27671 code in IRAM Code in flash (default, ICACHE_FLASH_ATTR), used 273120 / 1048576 bytes (26%) ║ SEGMENT BYTES DESCRIPTION ╚══ IROM 273120 code in flash </code></pre>
<p>With the info from <a href="https://github.com/bblanchon/ArduinoJson/issues/1442" rel="nofollow noreferrer">the link Fahad provided in the comments</a>, I can only offer a guess: Your ESP8266 board definitions are outdated and the old version of the ESP8266 board definitions contains a bug.</p> <p>There is an outdated URL to the ESP8266 board definition JSON floating around on the web. I <em>guess</em> you found that one. The URL still works, but is not updated anymore. Please check the version of your ESP8266 board definitions: Open the Board Manager (<code>Tools -&gt; Board -&gt; Board Manager</code>), search for ESP8266 and verify that the version is at least 3.1.2 (current version as of this writing; I don't know the lowest version where this bug is fixed).</p> <p>If the Board Manager does not offer to update to version 3.1.2 (or later), you may need to provide the current URL to the board definitions in <code>File -&gt; Preferences -&gt; Tab &quot;Settings&quot; -&gt; Additional Boards Manager URLs</code>. Remove the old ESP8266 URL, but don't remove URLs for <em>other</em> boards. Then try to update using the Board Manager again:</p> <pre><code>https://arduino.esp8266.com/stable/package_esp8266com_index.json </code></pre>
93852
|rotary-encoder|
Encoder giving value between steps
2023-07-17T18:35:13.137
<p>I'm trying to interface an encoder and a 1602 i2c display. My encoder seems to be giving an output between steps.</p> <p>I have tried to make my code as simple as possible and am outputting whether the encoder rotated clockwise or counter clockwise to serial. When I rotate the knob one physical step clockwise, '++' (separated by a new line) outputs to the serial monitor when I am expecting just '+'. The same occurs when rotating counter clockwise, except with '--' instead of '++'.</p> <p>Parts:</p> <ul> <li>ESP32 Dev Board</li> <li><a href="https://rads.stackoverflow.com/amzn/click/com/B07DM2YMT4" rel="nofollow noreferrer" rel="nofollow noreferrer">Rotary Encoder</a></li> </ul> <p>Code:</p> <pre><code>#define enc1 32 #define enc2 33 #define button 25 #define led 2; int oldPos1; int newPos1; int newPos2; void setup() { pinMode(enc1, INPUT_PULLUP); attachInterrupt(digitalPinToInterrupt(enc1),encRead,CHANGE); pinMode(enc2, INPUT_PULLUP); attachInterrupt(digitalPinToInterrupt(enc2),encRead,CHANGE); Serial.begin(115200); oldPos1 = digitalRead(enc1); } void encRead(){ newPos1 = digitalRead(enc1); newPos2 = digitalRead(enc2); if(oldPos1 != newPos1){ if (newPos1 == newPos2){ Serial.println(&quot;+&quot;); } else{ Serial.println(&quot;-&quot;); } } oldPos1 = newPos1; } void loop() { delay(10); } </code></pre>
<p>This is the kind of thing that can happen when you buy cheap parts that come with no documentation whatsoever: you don't know how they are supposed to work! Many rotary encoders have two detents per pulse: if you rotate them by a single detent, you get a single transition on each pin. If using such an encoder, you would indeed expect a single <code>+</code> or <code>-</code> printed per detent. But what about the encoder you bought? You can't tell, since there is no documentation!</p> <p>Quite fortunately, a helpful individual left a useful review on the product page you linked to. It can serve as an ersatz of datasheet:</p> <blockquote> <p>Each movement of the spindle from one detent to the next results in the encoder1 and encoder2 pins going through multiple transitions, not a single one (as you might expect).</p> <p>Assuming that you have tied the encoder pins to (say) 5V with a resistor, a rotation between detents, will produce a set of encoder transitions. For example: 11 10 00 01 11 (clockwise) or 11 01 00 10 11 (anti-clockwise).</p> </blockquote> <p>This explains the behavior you are experiencing.</p> <p>Side note: as jsotola writes in a comment, you should remove the <code>enc2</code> <code>attachInterrupt()</code>. As your interrupt handler explicitly ignores transitions in <code>enc2</code> (it does nothing unless <code>enc1</code> changed), there is no point in interrupting the processor for those ignored transitions.</p>
93860
|arduino-uno|board|
Whether my board analog pins shorted? I see same input on all
2023-07-18T16:48:53.813
<p>I am puzzled. I just connected 3.3 V input to the Analog pin A5 of the Arduino UNO. On the script, I am reading all the input pins. Surprizingly, all the pins are giving voltage as that of A5 pin. This made me think whether all of them shorted?</p> <p>code:</p> <pre><code>int a0_analogPin = A0; float a0_val = 0; int a1_analogPin = A1; float a1_val = 0; int a2_analogPin = A2; float a2_val = 0; int a3_analogPin = A3; float a3_val = 0; int a4_analogPin = A4; float a4_val = 0; int a5_analogPin = A5; float a5_val = 0; void setup() { Serial.begin(9600); // setup serial pinMode(a0_analogPin,INPUT); pinMode(a1_analogPin,INPUT); pinMode(a2_analogPin,INPUT); pinMode(a3_analogPin,INPUT); pinMode(a4_analogPin,INPUT); pinMode(a5_analogPin,INPUT); Serial.println(&quot;A0_val,A1_val,A2_val,A3_val,A4_val,A5_val&quot;); } void loop() { a0_val = analogRead(a0_analogPin)*5.0/1023.0; // read the input pin Serial.print(a0_val); // debug value Serial.print(&quot;,&quot;); a1_val = analogRead(a1_analogPin)*5.0/1023.0; // read the input pin Serial.print(a1_val); Serial.print(&quot;,&quot;); a2_val = analogRead(a2_analogPin)*5.0/1023.0; // read the input pin Serial.print(a2_val); Serial.print(&quot;,&quot;); a3_val = analogRead(a3_analogPin)*5.0/1023.0; // read the input pin Serial.print(a3_val); Serial.print(&quot;,&quot;); a4_val = analogRead(a4_analogPin)*5.0/1023.0; // read the input pin Serial.print(a4_val); Serial.print(&quot;,&quot;); a5_val = analogRead(a5_analogPin)*5.0/1023.0; // read the input pin Serial.println(a5_val); } </code></pre> <p>Board: <a href="https://i.stack.imgur.com/mStO4.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/mStO4.jpg" alt="enter image description here" /></a></p> <p>Serial Monitor: <a href="https://i.stack.imgur.com/8jiBs.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/8jiBs.png" alt="enter image description here" /></a></p>
<p>You are seeing crosstalk between the analog input channels. In the <a href="https://ww1.microchip.com/downloads/aemDocuments/documents/MCU08/ProductDocuments/DataSheets/ATmega48A-PA-88A-PA-168A-PA-328-P-DS-DS40002061B.pdf#G3.1738797" rel="nofollow noreferrer">datasheet of the microcontroller</a> you can see the analog input circuitry. See the capacitor labeled “C<sub>S/H</sub>”? This is the “sample and hold” capacitor. Its job is to hold the voltage being read while the ADC performs the conversion. When you measure channel A5, you are charging this capacitor to 3.3 V. Then, when you switch to a floating input, the capacitor has no path to discharge, and you end up measuring the same voltage.</p> <p>Actually, you do not measure exactly the same voltage. The reason is that each input pin has a parasitic capacitance. When you switch from A5 to A0, the charge in C<sub>S/H</sub> splits between this capacitor and the stray capacitance of the pin A0. Then, you switch to A1 and the remaining charge is split between C<sub>S/H</sub> and the stray capacitance of A1, and so on. Eventually, when you come back to A5, you charge again C<sub>S/H</sub> to the full 3.3 V and the cycle starts again. The net effect is that you are progressively moving charges between the successive pins. This is why the curves look like exponential relaxations, where each successive pin charges more slowly than the preceding one.</p> <p>The solution, as already written in other answers, is to avoid leaving the pin floating. The datasheet recommends making sure the connected source has an impedance no larger than 10 kΩ.</p>
93866
|programming|spi|bootloader|isp|
Programming barebones ATMega328 with external programmer and no bootloader
2023-07-18T20:56:41.590
<p>I have created a circuit with a barebones ATMega328. I also have an external programmer (Sparkfun's Pocket AVR Programmer)...</p> <p>Now I want to program a particular sketch... When uploading a sketch, do i also have to flash the bootloader beforehand?</p> <p>Or is it possible to upload the sketch directly to the microcontroller without a bootloader?</p>
<p>The Pocket AVR Programmer is just a standard ISP programmer, meaning it uses the ISP protocol built into the hardware of the microcontroller to write data to flash and EEPROM. That is also the way, that the bootloader got onto the microcontroller in the first place.</p> <p>The bootloader of the Arduino on the other hand is a small program to communicate over Serial (or USB depending on the Arduino board) and then write the data to flash and EEPROM.</p> <p>So: <strong>No, you don't need the bootloader, if you want to use the ISP programmer.</strong> Select your programmer in the corresponding menu of the Arduino IDE to use it.</p> <p>Though keep in mind, that you won't be able to upload a new sketch via Serial/USB without the bootloader. You can always use the ISP programmer to again write the bootloader to the microcontroller.</p>
93870
|esp8266|sensors|nodemcu|temperature-sensor|
NodeMcu V3 & BMe280 -> Temperature, Humidity, Pressure: value nan
2023-07-19T06:42:01.467
<p>I've just started playing around with a NodeMcu V3 and a <a href="https://www.ebay.it/itm/173602844579?mkcid=16&amp;mkevt=1&amp;mkrid=711-127632-2357-0&amp;ssspo=zP2vxbj4Rpe&amp;sssrc=4429486&amp;ssuid=P9XaWv98RhG&amp;var=&amp;widget_ver=artemis&amp;media=COPY" rel="nofollow noreferrer">BME280 sensor</a>.</p> <p><a href="https://i.stack.imgur.com/t7Uqi.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/t7Uqi.png" alt="enter image description here" /></a></p> <p>wiring</p> <pre><code>VCC -&gt; 3.3V GND -&gt; GND SCL -&gt; D1 (GPIO5) SDA -&gt; D2 (GPIO4) </code></pre> <p>I've tried this sketch / I2C scanner: it finds the BME280 at 0x76</p> <pre><code>#include &lt;Wire.h&gt; // Set I2C bus to use: Wire, Wire1, etc. #define WIRE Wire void setup() { WIRE.begin(); Serial.begin(9600); while (!Serial) delay(10); Serial.println(&quot;\nI2C Scanner&quot;); } void loop() { byte error, address; int nDevices; Serial.println(&quot;Scanning...&quot;); nDevices = 0; for(address = 1; address &lt; 127; address++ ) { // The i2c_scanner uses the return value of // the Write.endTransmisstion to see if // a device did acknowledge to the address. WIRE.beginTransmission(address); error = WIRE.endTransmission(); if (error == 0) { Serial.print(&quot;I2C device found at address 0x&quot;); if (address&lt;16) Serial.print(&quot;0&quot;); Serial.print(address,HEX); Serial.println(&quot; !&quot;); nDevices++; } else if (error==4) { Serial.print(&quot;Unknown error at address 0x&quot;); if (address&lt;16) Serial.print(&quot;0&quot;); Serial.println(address,HEX); } } if (nDevices == 0) Serial.println(&quot;No I2C devices found\n&quot;); else Serial.println(&quot;done\n&quot;); delay(5000); // wait 5 seconds for next scan } </code></pre> <p>Then I've tried library BMx280I2C into this sketch:</p> <pre><code>#include &lt;Wire.h&gt; #include &lt;BMx280I2C.h&gt; BMx280I2C bmx280(0x76); void setup() { Serial.begin(9600); // Setup BMx280 Wire.begin(); bmx280.begin(); bmx280.resetToDefaults(); bmx280.writeOversamplingPressure(BMx280I2C::OSRS_P_x16); bmx280.writeOversamplingTemperature(BMx280I2C::OSRS_T_x16); bmx280.writeOversamplingHumidity(BMx280I2C::OSRS_H_x16); } void loop() { // T,P,H measurements bmx280.measure(); do{ delay(100); Serial.println(&quot;No value, yet!&quot;); } while (!bmx280.hasValue()); Serial.print(&quot;Pressure &quot;); Serial.println(bmx280.getPressure()); Serial.print(&quot;Temperature &quot;); Serial.println(bmx280.getTemperature()); Serial.print(&quot;Humidity &quot;); Serial.println(bmx280.getHumidity()); delay(1000); } </code></pre> <p>the output is always and only:</p> <blockquote> <pre><code>-&gt; No value, yet! -&gt; Pressure nan -&gt; Temperature nan -&gt; Humidity nan </code></pre> </blockquote> <p>Why? How can I understand the origin of the problem?Thanks!</p>
<p>Solved with <a href="https://www.arduino.cc/reference/en/libraries/adafruit-bme280-library/" rel="nofollow noreferrer">Adafruit library</a></p> <pre><code>#include &lt;Wire.h&gt; #include &lt;Adafruit_Sensor.h&gt; #include &lt;Adafruit_BME280.h&gt; #define SEALEVELPRESSURE_HPA (1013.25) Adafruit_BME280 bme; void setup() { Serial.begin(9600); if (!bme.begin(0x76)) { Serial.println(&quot;Could not find a valid BME280 sensor, check wiring!&quot;); while (1); } } void loop() { Serial.print(&quot;Temperature = &quot;); Serial.print(bme.readTemperature()); Serial.println(&quot; *C&quot;); Serial.print(&quot;Humidity = &quot;); Serial.print(bme.readHumidity()); Serial.println(&quot; %&quot;); Serial.print(&quot;Pressure = &quot;); Serial.print(bme.readPressure() / 100.0F); Serial.println(&quot; hPa&quot;); Serial.print(&quot;Approx. Altitude = &quot;); Serial.print(bme.readAltitude(SEALEVELPRESSURE_HPA)); Serial.println(&quot; m&quot;); Serial.println(); delay(2000); } </code></pre>
93873
|eeprom|
How EEMEM maps the variables? (avr/eeprom.h)
2023-07-19T14:36:14.127
<p>I can store and restore my data with avr/eeprom.h if I don't change the sketch.</p> <ol> <li>I have a sketch that stores the data. After power cycle of the device the data are fine.</li> <li>If I change the sketch with Serial.print statements (I want to re-read the data on-screen) the sketch seeks the data in wrong addresses of EEPROM, although I can verify with another sketch that the data are fine.</li> </ol> <p>More detailed: I store around 50 bytes, but I verified the location for only the 4 bytes variable. I can see that this variable is at the start of the EEPROM (address: 0). But the second sketch seeks the data on address 30. Not even close.</p> <p>To my understanding avr/eeprom.h is more easy to use since you don't need to police the location of data. But it seems that if change (what?) in your sketch it seeks the data on other locations although on eeprom are fine.</p> <p>In other words, it's like if I change the firmware (not the EEMEM variables / definitions!), that firmware seeks the data on different places.</p> <p>I understood something wrong?</p> <p>In my situation is better to use the arduino EEPROM.h with static location of EEPROM addresses?</p> <p>Fun fact. Google Bard seems it got it completely wrong:</p> <blockquote> <p>What are the differences of avr/eeprom.h and EEPROM.h from arduino?</p> </blockquote> <p>(Google Bard Answer)</p> <blockquote> <p>The avr/eeprom.h and EEPROM.h libraries in Arduino are both used to access the EEPROM memory on AVR microcontrollers. However, there are some key differences between the two libraries. avr/eeprom.h is a lower-level library that provides direct access to the EEPROM registers. This means that it can be used to access any location in the EEPROM, but it also requires more code and can be more error-prone. EEPROM.h is a higher-level library that provides a more user-friendly interface to the EEPROM. It only allows you to access addresses that are within the range of the EEPROM, but it is easier to use and less error-prone. In general, avr/eeprom.h should only be used if you need to access specific locations in the EEPROM that are not within the range of EEPROM.h. Otherwise, EEPROM.h is the preferred library to use.</p> </blockquote> <p>Edit: avr-objdump of eeprom section</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>Prints on Sketch</th> <th>Without prints</th> <th>Prints both on Library and Sketch</th> </tr> </thead> <tbody> <tr> <td>00810000 &lt;eeprom_lw_dev_nonce&gt;:</td> <td>00810000 &lt;eeprom_lw_f_nwk_s_int_key&gt;:</td> <td>00810000 &lt;eeprom_lw_dev_addr&gt;:</td> </tr> <tr> <td>00810002 &lt;eeprom_lw_f_nwk_s_int_key&gt;:</td> <td>00810010 &lt;eeprom_lw_s_nwk_s_int_key&gt;:</td> <td>00810004 &lt;eeprom_lw_dev_nonce&gt;:</td> </tr> <tr> <td>00810012 &lt;eeprom_lw_s_nwk_s_int_key&gt;:</td> <td>00810020 &lt;eeprom_lw_has_joined&gt;:</td> <td>00810006 &lt;eeprom_lw_f_nwk_s_int_key&gt;:</td> </tr> <tr> <td>00810022 &lt;eeprom_lw_join_nonce&gt;:</td> <td>00810021 &lt;eeprom_lw_dev_nonce&gt;:</td> <td>00810016 &lt;eeprom_lw_s_nwk_s_int_key&gt;:</td> </tr> <tr> <td>00810026 &lt;eeprom_lw_has_joined&gt;:</td> <td>00810023 &lt;eeprom_lw_join_nonce&gt;:</td> <td>00810026 &lt;eeprom_lw_nwk_s_enc_key&gt;:</td> </tr> <tr> <td>00810027 &lt;eeprom_lw_tx_frame_counter&gt;:</td> <td>00810027 &lt;eeprom_lw_tx_frame_counter&gt;:</td> <td>00810036 &lt;eeprom_lw_app_s_key&gt;:</td> </tr> <tr> <td>00810029 &lt;eeprom_lw_rx_frame_counter&gt;:</td> <td>00810029 &lt;eeprom_lw_nwk_s_enc_key&gt;:</td> <td>00810046 &lt;eeprom_lw_has_joined&gt;:</td> </tr> <tr> <td>0081002b &lt;eeprom_lw_nwk_s_enc_key&gt;:</td> <td>00810039 &lt;eeprom_lw_rx_frame_counter&gt;:</td> <td>00810047 &lt;eeprom_lw_rx_frame_counter&gt;:</td> </tr> <tr> <td>0081003b &lt;eeprom_lw_app_s_key&gt;:</td> <td>0081003b &lt;eeprom_lw_app_s_key&gt;:</td> <td>00810049 &lt;eeprom_lw_tx_frame_counter&gt;:</td> </tr> <tr> <td>0081004b &lt;eeprom_lw_dev_addr&gt;:</td> <td>0081004b &lt;eeprom_lw_dev_addr&gt;:</td> <td>0081004b &lt;eeprom_lw_rx2_data_rate&gt;:</td> </tr> <tr> <td>0081004f &lt;eeprom_lw_rx2_data_rate&gt;:</td> <td>0081004f &lt;eeprom_lw_rx1_delay&gt;:</td> <td>0081004c &lt;eeprom_lw_rx1_data_rate_offset&gt;:</td> </tr> <tr> <td>00810050 &lt;eeprom_lw_rx1_data_rate_offset&gt;:</td> <td>00810050 &lt;eeprom_lw_rx2_data_rate&gt;:</td> <td>0081004d &lt;eeprom_lw_join_nonce&gt;:</td> </tr> <tr> <td>00810051 &lt;eeprom_lw_rx1_delay&gt;:</td> <td>00810051 &lt;eeprom_lw_rx1_data_rate_offset&gt;:</td> <td>00810051 &lt;eeprom_lw_rx1_delay&gt;:</td> </tr> </tbody> </table> </div> <p>Image kept for historical reasons.</p> <p>1st window: Serial.print(s) only in sketch. 2nd window: without Serial.print(s) 3rd window: Serial.print(s) both on sketch and library. <a href="https://i.stack.imgur.com/5h5uO.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/5h5uO.png" alt="EEMEM from avr-objdump -D" /></a></p>
<p>I wouldn't rely on the compiler necessarily allocating variables at any particular memory address, especially after what you posted. You can make a little include file that simplifies reading from/writing to EEPROM, as below:</p> <pre class="lang-c++ prettyprint-override"><code>#include &lt;Arduino.h&gt; // for type definitions #include &lt;EEPROM.h&gt; template &lt;typename T&gt; unsigned int EEPROM_writeAnything (int ee, const T&amp; value) { const byte* p = (const byte*)&amp;value; unsigned int i; for (i = 0; i &lt; sizeof(value); i++) EEPROM.write(ee++, *p++); return i; } template &lt;typename T&gt; unsigned int EEPROM_readAnything (int ee, T&amp; value) { byte* p = (byte*)&amp;value; unsigned int i; for (i = 0; i &lt; sizeof(value); i++) *p++ = EEPROM.read(ee++); return i; } </code></pre> <p>Then you can do something like this:</p> <pre class="lang-c++ prettyprint-override"><code>int someData; // declare a local variable ... EEPROM_readAnything (0, someData); // read into it, from address zero in EEPROM ... someData++; EEPROM_writeAnything (0, someData); // write it back out, to address zero </code></pre> <p>The library above uses templates to manage any size data, so you can write or write ints, arrays, etc. One possibility would be to make a struct and read/write the whole thing every time. That way you don't need to keep track of offsets (the whole struct could be written to address 0).</p> <hr /> <p>Here's an example of doing that, using <code>offsetof</code> to manage the offsets of individual fields inside your overall struct, the thing that is stored in the EEPROM.</p> <pre class="lang-c++ prettyprint-override"><code>#include &lt;EEPROMAnything.h&gt; const long MAGIC_ID = 'Nick'; // information in EEPROM typedef struct { unsigned long magic; // to see if we initialised EEPROM unsigned long counter; char myName [30]; } myInformation; void setup() { Serial.begin (115200); Serial.println (&quot;Starting ...&quot;); // see if EEPROM initialised unsigned long magicTest; EEPROM_readAnything (offsetof (myInformation, magic), magicTest); if (magicTest != MAGIC_ID) { Serial.println (&quot;Initialising EEPROM&quot;); myInformation initStuff; initStuff.magic = MAGIC_ID; initStuff.counter = 0; strcpy (initStuff.myName, &quot;Nick Gammon&quot;); EEPROM_writeAnything (0, initStuff); // write whole struct } // end of if not initialised // find counter unsigned long myCounter; EEPROM_readAnything (offsetof (myInformation, counter), myCounter); Serial.print (&quot;Counter is &quot;); Serial.println (myCounter); // find name char hisName [sizeof (myInformation().myName)]; EEPROM_readAnything (offsetof (myInformation, myName), hisName); Serial.print (&quot;Name is &quot;); Serial.println (hisName); // add to counter myCounter++; // write counter back EEPROM_writeAnything (offsetof (myInformation, counter), myCounter); // write whole struct Serial.println (&quot;Done.&quot;); } // end of setup void loop() { // whatever } // end of loop </code></pre>
93876
|arduino-uno|analogread|electronics|analog|
How does actually arduino measure voltage?
2023-07-19T15:24:21.233
<p>I am not interested into the AnalogRead() part, but rather on how he converts 5 or 2 V into a number between 0 and 1023. How does it practically do it to convert the voltage level into a number or into bits to then send to the processor? Thanks in advance</p>
<p>The ATmega328P features a 10-bit successive approximation ADC. The ADC is connected to an 8-channel Analog Multiplexer.</p> <p><a href="https://i.stack.imgur.com/KpFXc.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/KpFXc.png" alt="ADC schematic" /></a></p> <p>First, an input is selected from the multiplexer on the left. This allows any of 8 input channels to be active at one time (but only one). These are: A0 to A5 on the Uno (some boards also have A6 and A7). There are also additional input channels (not shown) which also allows the selection of:</p> <ul> <li>The internal temperature sensor</li> <li>Ground</li> <li>Bandgap reference voltage</li> </ul> <p>The input channel (multiplexer output) is connected to a &quot;sample and hold&quot; capacitor, as shown. Once an analog conversion starts the switch is opened after 1.5 ADC cycles (12 µs with the default prescaler of 128) so that the capacitor retains its current reading (ie. it holds it) so that the input voltage can now change without affecting the result. This would be useful for fast-changing signals, as the whole conversion can take 104 µs (depending on the prescaler).</p> <p>To work out the voltage the logic applies the analog reference voltage (ARef) divided down by a DAC (digital-to-analog converter) under the control of the ADC logic. The output of the DAC is sent to the comparator which determines if the input voltage is higher or lower than the reference voltage, at its current divided state. For example, the high-order bit would be set or cleared by setting the DAC to divide the reference voltage by 2 (ie. 2.5V if ARef is 5V). If the input is higher than 2.5V then the high-order bit in the result is set. This takes one ADC cycle (8 µs at the default prescaler of 128 with a 16 MHz processor clock).</p> <p>To get the next result bit the DAC would be set to the next step (ie. 0.25 of ARef or 0.75 of ARef depending on whether the first bit was set or not) and another comparison done. This process is repeated for all 10 bits.</p>
93894
|esp32|wifi|communication|
RX and TX pins on esp32
2023-07-21T10:18:09.857
<p>hello guys i'm new to this field i really need your help i want to wire a GSM module (SIM808) to a ESP32 board using the TX and RX pins so the pins are labeled RX and TX no pin number like the others how can i declare them in the code. i already tested the code on an arduino uno on pins 0 and 1 (RX and TX) and it works fine here is the board i'm using : i already tried using pins 16 and 17 but didn't work i need to try using pins number 40 and 41 according to image below <a href="https://i.stack.imgur.com/RY872.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/RY872.jpg" alt="enter image description here" /></a></p>
<p>First off, thank you for all the guidance and support you've provided. As a beginner in the world of Arduino and embedded systems, it's been tremendously helpful.</p> <p>The main issue I was facing had to do with not knowing how to declare the TX and RX pins in my C++ code, especially when these pins weren't labelled with their GPIO numbers like the others on my ESP32 board. After a bit of research and reading through your comments, I learned that these pins can simply be declared using their GPIO numbers, which are indicated on the schematic of the board.</p> <p>For instance, to utilize RX0 and TX0, they need to be declared as 3 and 1 respectively. Here's an example:</p> <pre><code> #define RXD 3 //RXD #define TXD 1 //TXD HardwareSerial SIM808(2); void setup() { // // SIM808.begin(9600, SERIAL_8N1, RXD, TXD); } </code></pre> <p>I was able to get the SIM808 module working with this method, but I'm noticing that the system isn't always consistent. Sometimes it takes a long time to execute commands, which is something I will have to look into.</p> <p>I just wanted to express my gratitude for the warm welcome and helpful guidance I've received here. This being my first post, I was worried about asking a &quot;dumb question,&quot; but the community has been nothing but supportive.</p> <p>As I continue to learn and explore more about embedded systems, I'm sure I'll be back with more questions, and hopefully, in time, some answers of my own to contribute!</p>
93900
|arduino-ide|arduino-nano|wireless|lora|arduino-esplora|
LoRa Ra-02 Module begin and beginPacket not working in Arduino Nano
2023-07-21T21:24:09.570
<p>Here there, recently I am testing <strong>Lora Ra-02 module</strong> I saw many videos and it is easy to set up, according to this schematic:</p> <blockquote> <p>LoRa SX1278 Module-----Arduino Nano Board</p> <p>3.3V-------</p> <p>Gnd---------Gnd</p> <p>En/Nss------D10</p> <p>G0/DIO0------D2</p> <p>SCK---------D13</p> <p>MISO----------D12</p> <p>MOSI----------D11</p> <p>RST-------------D9</p> </blockquote> <p>I am using a very common library called <a href="https://github.com/sandeepmistry/arduino-LoRa" rel="nofollow noreferrer">sandeepmistry</a>. and I tried this code:</p> <pre class="lang-c prettyprint-override"><code>#include &lt;SPI.h&gt; #include &lt;LoRa.h&gt; int counter = 1; void setup() { Serial.begin(9600); while (!Serial); Serial.println(&quot;LoRa Sender&quot;); if (!LoRa.begin(433E6)) { Serial.println(&quot;Starting LoRa failed!&quot;); while (1); } } void loop() { Serial.print(&quot;Sending packet: &quot;); Serial.println(counter); // send packet LoRa.beginPacket(); LoRa.print(&quot;hello &quot;); LoRa.print(counter); LoRa.endPacket(); counter++; delay(500); } </code></pre> <p>When I run it, it just sticks in this line {Serial.println(&quot;<strong>Starting LoRa failed!</strong>&quot;);}</p> <p>Then I updated the code and tried to reduce the SPI Frequency because I am using <strong>Arduino Nano</strong> now the code is this:</p> <pre class="lang-c prettyprint-override"><code>#include &lt;SPI.h&gt; #include &lt;LoRa.h&gt; int counter = 1; int frequency = 8E6; // Set the desired frequency here void setup() { Serial.begin(9600); while (!Serial); Serial.println(&quot;LoRa Sender&quot;); LoRa.setSPIFrequency(frequency); // Add the missing semicolon here if (!LoRa.begin(433E6)) { Serial.println(&quot;Starting LoRa failed!&quot;); while (1); } } void loop() { Serial.print(&quot;Sending packet: &quot;); Serial.println(counter); // send packet LoRa.beginPacket(); LoRa.print(&quot;hello &quot;); LoRa.print(counter); LoRa.endPacket(); counter++; delay(500); } </code></pre> <p>This code passes the line <strong>Starting LoRa failed!</strong> but it again stuck in here</p> <blockquote> <p>LoRa Sender Sending packet: 1</p> </blockquote> <p>So why won't it do <code>LoRa.beginPacket();</code> and loop the code? Why does it stop here?</p>
<p>Have you set the pins properly? Try doing:</p> <pre class="lang-c prettyprint-override"><code> LoRa.setPins(csPin, resetPin, irqPin);// set CS, reset, IRQ pin </code></pre> <p>There is a problem with the way your SX1276 is connected to the board, which is why <code>.begin()</code> returns false.</p>
93902
|interrupt|softwareserial|attiny|sleep|attiny85|
ATtiny85 with sleep and serial
2023-07-22T00:15:04.373
<p>I want to communicate over serial to another device (dfplayer) and also set the microcontroller into sleep mode.</p> <p>The ATtiny85 does not have a hardware serial pin so I need to use a virtual serial (like <code>SoftwareSerial.h</code>)</p> <p>I've googled a lot and tried a lot of things but it basically seems to come always to the same problem. <code>SoftwareSerial</code> (or <code>NeoSWSerial</code>) do not work with <code>avr/sleep</code>. Something to do with interrupts,</p> <blockquote> <p>NeoSWSerial.cpp.o (symbol from plugin): In function <code>NeoSWSerial::read()': (.text+0x0): multiple definition of </code>__vector_2' .pio\build\attiny85\src\main.cpp.o (symbol from plugin):(.text+0x0): first defined here</p> </blockquote> <p>AltSoftSerial won't work because it requires a 16bit timer which the ATtiny does not have__</p> <p>Is there anything I can do about this?</p> <hr /> <p>What I actually want to do</p> <p>Connect 6 buttons with 6 different resistors to a single ADC pin of the controller. When a button is pressed wake up the device /if necessary), read the ADC value, pick a track based on that value and then play the track on the dfplayer.</p> <p>After a while, if no button is pressed, put the dfplayer and the mcu to sleep. And that's why I need the mcu at all. You can't set the dfplayer to sleep or wake it up without serial</p> <hr /> <p>Update:</p> <p>I confused SPI and Serial indeed. I need to use serial communication</p> <p>I want to send and receive packages. Send: <code>InitCommand</code>, Receive: <code>PlayerInitialized</code> / <code>InitializationFailed</code>. And so on.Well it's some hex codes of course but you get the point I think</p> <p>My flow should basiclly look like this:</p> <p>boot/wakeup // &lt;-- this is where I need the interrupt, don't I?<br /> read adc value<br /> pick track number based on adc value<br /> send PlayTrack command to DFPlayer<br /> delay x ms<br /> send Sleep command to DFPlayer<br /> go back to sleep</p> <p>But the issue is in the combination of the Sleep and SoftwareSerial library. It's not the interrupt that is an issue. At least not yet</p>
<blockquote> <p>boot/wakeup // &lt;-- this is where I need the interrupt, don't I?</p> </blockquote> <p>Is the interrupt to detect that you have pressed one of the buttons? If you have that then you shouldn't need to use a timer to wake up.</p> <p>If you connect your buttons with resistors in such a way that any button at all will send at least 0.6Vcc (ie. 3V upwards for a 5V system) then that could be configured to generate an interrupt (a rising interrupt). So you might set up the resistors so the buttons send 3.2V, 3.5V, 3.8V, 4.1V, 4.4V and 4.7V. That gives you six different voltages and they are all high enough to be considered &quot;high&quot; on a digital pin. Then make that pin generate the interrupt and also do the ADC reading on it once you wake up.</p> <p>Then you can put the processor into a deep sleep until a button is pressed. While the track is playing you might also set up a watchdog timer interrupt so that you can wake up and check if it is time to put the player to sleep as well.</p>
93910
|arduino-uno|
"Best" architecture for handle events
2023-07-22T19:15:08.770
<p>I come from web world, so i usually code in a more procedurally manner, so the loop is a bit difficult to handle.</p> <p>i mean if i do something like <code>if(condition) doSomething()</code> it will exec <code>doSomething()</code> a lot, or a click of a button....</p> <pre class="lang-cpp prettyprint-override"><code>bool condition = false; void loop(){ if(condition){ doSomething(); } } void doSomething(){ condition = false; // ........ } </code></pre> <p>iam doing things like this, but i feel its wrong somehow</p> <p>so iam struggling why could be the &quot;best&quot; architecture to execute <code>doSomething()</code> only once, in a way it not become a hell of state management, some kind of event driven, event sourcing or something more battle tested for arduino</p> <p>iam totally newbie in this hardware/arduino world</p>
<p>Coming from the Web world, you are most likely used to work in a single-threaded environment (save for Web workers). You have been trained to program in a non-blocking fashion, as blocking the browser's UI thread would freeze the user interface. This is actually <strong>a valuable asset</strong> when moving to Arduino programming. Most Arduino programs run on a single-threaded, bare-metal platform. Non-blocking code is a must for all but the most trivial programs, and is not easy to master for newcomers.</p> <p>The most striking difference between an Arduino and your typical JavaScript environment (be it a browser or Node.js) is that in JavaScript the event loop is <em>implicit</em>. You do not see it, but it runs under the hood of your interpreter. It looks conceptually like this:</p> <pre class="lang-cpp prettyprint-override"><code>void JavaScript_event_loop() { if (there_is_a_pending_event()) { dispatch_the_event_to_the_registered_callback(); } } </code></pre> <p>On the Arduino, however, you have to write the event loop yourself. Most often you do not need full-blown event queue management, as you know beforehand the set of events your program will have to handle. Your typical Arduino loop should normally look like this:</p> <pre class="lang-cpp prettyprint-override"><code>void loop() { if (event_foo_happened()) handle_event_foo(); if (event_bar_happened()) handle_event_bar(); if (event_baz_happened()) handle_event_baz(); // etc... } </code></pre> <p>There are a few recurring idioms for testing common events. Here are some examples:</p> <pre class="lang-cpp prettyprint-override"><code>// Handle a periodic event (like setInterval()). uint32_t now = millis(); static uint32_t last_event_time; if (now - last_event_time &gt;= event_period) { // Use `last_event_time = now;` instead of this if you want to // guarantee a minimal interval between events: last_event_time += event_period; // this avoids systematic drift handle_periodic_event(); } // Handle a rising edge on an input_pin. uint8_t pin_state = digitalRead(pin); static uint8_t previous_pin_state; if (previous_pin_state == LOW &amp;&amp; pin_state == HIGH) handle_input_rising_edge(); previous_pin_state = pin_state; // Handle Serial data. if (Serial.available()) handle_input_byte(Serial.read()); // Handle a push button with a debouncing library. button.update(); if (button.fell()) handle_button_press(); </code></pre> <p>A few recommended readings:</p> <ul> <li>The <a href="https://www.arduino.cc/en/Tutorial/BuiltInExamples/BlinkWithoutDelay" rel="nofollow noreferrer">Blink Without Delay</a> Arduino tutorial shows how to handle periodic events</li> <li><a href="https://www.majenko.co.uk/blog/our-blog-1/reading-serial-on-the-arduino-27" rel="nofollow noreferrer">Reading Serial on the Arduino</a> is a tutorial showing how to buffer serial input in order to handle one full message at a time</li> <li><a href="https://github.com/thomasfredericks/Bounce2" rel="nofollow noreferrer">Bounce2</a> is an example of a button-debouncing library</li> <li><a href="https://www.majenko.co.uk/blog/our-blog-1/the-finite-state-machine-26" rel="nofollow noreferrer">The Finite State Machine</a> is a nice tutorial on writing finite state machines, which sooner or later you will need for handling some situations in a non-blocking way</li> </ul> <hr /> <p><strong>Edit</strong>: Regarding the example code you posted, I would like to rewrite your <code>loop()</code> like this:</p> <pre class="lang-cpp prettyprint-override"><code>void loop() { if (condition) { doSomething(); condition = false; // &lt;- move this out of doSomething() } } </code></pre> <p>It doesn't look like a big change, but there is an idea here that can help make your code more readable and maintainable. The idea is to think of your program in terms of “events” you have to respond to. This should feel natural to someone raised on JavaScript, and it is also a good approach for programming microcontrollers. You then want to handle the event detection/dispatching and the event response as separate problems. The function <code>doSomething()</code> should not have to care about the <code>condition</code> variable, as it is only used to handle the event detection and dispatching, which is the responsibility of the event loop.</p> <blockquote> <p>When i said to execute once I mean, when press a button, it should do something only once, this control of what should/was executed is a bit tricking, can go out of control and became a mess.</p> </blockquote> <p>To detect a button press you <em>do</em> have to manage some state, there is no way around it. Your program should not respond to the <em>state</em> of the button (pressed or released) but instead to specific <em>transitions</em> of this state (press or release events).</p> <p>In its most basic form, the problem is about detecting a falling edge (or rising edge, depending on how the button is wired) on the input signal. This is handled by remembering the state you had on the previous loop iteration, and comparing this previous state with the state you are reading right now, as show in the “Handle a rising edge on an input pin” example above.</p> <p>Real buttons have an additional issue, namely mechanic bounce: when the button is actuated, the signal can go through many fast transitions before settling into a stable state. In order to deal with this, you have to look at the timing of the transitions and sort out the legit ones from the spurious ones. This is called <a href="https://learn.adafruit.com/make-it-switch/debouncing" rel="nofollow noreferrer">debouncing</a>. There are a few libraries out there than can handle this for you. Most will also do edge detection, which makes handling button presses as simple as testing for <code>button.fell()</code> (again, see example above). Some will even report distinct event types for short press, long press and double press.</p>
93920
|led|
Does the UNO R4 still have the standard on-board led on pin 13?
2023-07-23T19:14:45.520
<p>I need to add support for the UNO R4 (both models) for a library I'm maintaining. The library uses the LED on pin 13 as status indicator. I can't find any information whether that LED is still there on the R4 Minima and Wifi boards. The R4 Wifi has this nice LED matrix, so the other LED might be gone for it.</p>
<p>The schematics for the R4 Minima and Wifi boards can be found at: <a href="https://docs.arduino.cc/resources/schematics/ABX00080-schematics.pdf" rel="nofollow noreferrer">https://docs.arduino.cc/resources/schematics/ABX00080-schematics.pdf</a> and <a href="https://docs.arduino.cc/resources/schematics/ABX00087-schematics.pdf" rel="nofollow noreferrer">https://docs.arduino.cc/resources/schematics/ABX00087-schematics.pdf</a> . Pin 13 is also labeled SCK. A LED is attached to this pin.</p>
93932
|arduino-uno|keyboard|
How to use Arduino Uno as PS/2 to USB converter for typical keyboard usages?
2023-07-24T14:33:54.423
<p>I'm beginner in Arduino and recently programmed an Arduino uno board with various PS/2 to USB converters. They work when typing in Serial Monitor of Arduino IDE, but not in the other programs such as Notepad.</p> <p><a href="https://i.stack.imgur.com/hhZVB.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/hhZVB.png" alt="enter image description here" /></a></p> <p>How can I connect the board as HID keyboard for usual works with my PS/2 keyboard?</p> <p><strong>Update:</strong></p> <p>As @KIIV mentioned in the comments, Uno hasn't native USB and his suggestion is to start with boards such as Leonardo.</p> <p>I want to ask, what is the straightforward way of using Uno for this purpose?</p>
<p>As the Uno has no generic USB module, it generally works only as a virtual serial device. Without additional hardware you cannot make a Uno work as a USB keyboard. In principle.</p> <p>A possible solution is the usage of <a href="https://www.obdev.at/products/vusb/index.html" rel="nofollow noreferrer">V-USB</a>. This nice library uses <a href="https://en.wikipedia.org/wiki/Bit_banging" rel="nofollow noreferrer">bit-banging</a> to realize low-speed USB communication. A USB keyboard commonly is such a low-speed USB device.</p> <p>Another possible solution is an accompanying software &quot;driver&quot; on the PC. It will receive the key events via the USB serial port and translate them to key events for the operating system. But I'm sure you will not want this.</p>
93938
|c++|
Overhead of using 'new' to create object in dynamic ram vs automatic to create on stack
2023-07-24T23:24:10.977
<p>Let's suppose I have a class named <code>Foo</code>, and <code>sizeof(Foo)</code> is 10 bytes.</p> <p>As I understand it, creating a Foo with 'automatic' scope (on the stack) has zero overhead. If the Object occupies 10 bytes, it consumes 10 bytes on the stack. Period.</p> <p>I'm kind of fuzzy about how creating objects with 'new' works on an 8-bit AVR. I know that 'new' ultimately calls malloc(), and that on Windows/Linux, malloc() ultimately asks the operating system for memory whose management is up to the OS itself. But... with 8-bit AVR, there <em>is no</em> operating system. So, presumably, something else has ultimate responsibility for managing its heap. And presumably, there's some kind of overhead involved so it can keep track of which bytes have been returned to it by a destructor, and which ones are still in use.</p> <p>So... using the hypothetical 10-byte <code>Foo</code> as an example... if I make 7 sequential calls in a row to <code>new Foo()</code>, how many bytes will it <em>actually</em> burn through (including overhead)?</p> <p>For objects that have to be instantiated via <code>new</code>, but will persist &quot;forever&quot; (until the next reset), is there any special syntax that tells the compiler/malloc()/whatever, &quot;This object will <strong>never</strong> be destroyed, so there's no need to preserve any information that would otherwise be necessary to release its memory eventually&quot;?</p> <hr /> <p>Giving this a bit of context, assume <code>View</code> is a class with multiple templated subclasses (let's say, <code>TemperatureView&lt;int, int, int, int&gt;</code> and <code>LabelView&lt;int, int, int, const char*&gt;</code>), and I'm doing something like this:</p> <pre><code>const PROGMEM char* pLABEL = &quot;Foo:&quot;; View* views[] = { (new TemperatureView&lt;0,3,0,2&gt;{}), (new LabelView&lt;1,4,0,pLABEL&gt;{}) }; </code></pre> <p>I'm trying to figure out just how big of a penalty hit (in terms of wasted ram from overhead) I'm taking by rolling it all into one nice, neat combined declaration instead of doing something like:</p> <pre><code>const PROGMEM char* pLABEL = &quot;Foo:&quot;; TemperatureView&lt;0,3,0,2&gt; firstTemp {}; LabelView&lt;1,4,0,pLABEL&gt; firstLabel {}; View* views[] = { &amp;firstTemp, &amp;firstLabel }; </code></pre> <p>(I originally wanted to put the objects whose addresses were being added to views[] in automatic/stack, but apparently, that's taboo because the compiler thinks the array will outlive the objects whose addresses would otherwise be stored there)</p>
<p>Just as a small complement to the previous answer... The documentation of the avr-libc has a whole page discussing the workings of <code>malloc()</code>. The section titled <a href="https://www.nongnu.org/avr-libc/user-manual/malloc.html#malloc_impl" rel="nofollow noreferrer">Implementation details</a> states:</p> <blockquote> <p>Dynamic memory allocation requests will be returned with a two-byte header prepended that records the size of the allocation. This is later used by <code>free()</code>. The returned address points just beyond that header.</p> </blockquote> <p>This is consistent Nick Gammon's experimental finding.</p>
93950
|arduino-uno|digital|potentiometer|
Digital Pot with Arduino
2023-07-26T05:09:00.763
<p>I am a newbie in electronics. Please correct me if I am wrong. I am replacing a pot with a digital pot (DS3502) in a circuit. The Vcc of the circuit is 12V. But the digital pot can have a maximum of 5.5V as Vcc. I am controlling the digital pot with an Arduino UNO. Can I use 5V from the Arduino as the Vcc of the digital pot and 12V as the Vcc of the circuit? I kept the ground common for both.</p> <p>The connection is as below:</p> <p>DS3502 Arduino Uno</p> <p>VCC --- 5V</p> <p>GND --- GND</p> <p>SDA --- A4</p> <p>SCL --- A5</p> <p>DS3502 Circuit</p> <p>RL --- GND</p> <p>RW --- Circuit</p> <p><a href="https://i.stack.imgur.com/O4pYS.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/O4pYS.jpg" alt="enter image description here" /></a></p> <p>This is a constant current circuit of 21mA, to drive a laser. But I want to slightly tune the intensity of laser using the digital pot. So I am replacing it with digital pot. But I am getting an open connection in the place of resistor. I have only use RL and RW to circuit. RH is kept opened. Do I need to connect RH and V bias to 12V(Vcc of my constant current circuit)? I don't have much knowledge in circuits. Please spare me if I am wrong</p>
<p>If you look at <a href="https://www.analog.com/media/en/technical-documentation/data-sheets/DS3502.pdf" rel="nofollow noreferrer">the datasheet</a> it mentions that Vcc can be from 2.5V to 5.5V, and clearly the I2C connection is referenced to Gnd. Therefore you would connect the Uno to the DS3502 in the usual way (Gnd, Vcc, SDA and SCL).</p> <p>The &quot;digital pot&quot; side has a separate input (V+) which can be from 4.5V to 15.5V.</p> <blockquote> <p>Can I use 5V from the Arduino as the Vcc of the digital pot and 12V as the Vcc of the circuit?</p> </blockquote> <p>Your terminology is a bit loose here. You can use 5V from the Arduino to the Vcc pin of the pot (pin 3) and 12V to V+ and RH (pins 6 and 9). The output will be on RW (the wiper, pin 7).</p> <p>It also looks like you would connect Gnd and RL (pins 2 and 8) to Gnd on the Arduino.</p> <p>Although, conceivably I think, you could connect Gnd (pin 2) to Gnd on the Arduino, and RL (pin 8) to the Gnd of the &quot;other circuit&quot; - the one you are controlling. It looks like they are separate.</p> <p>I think you might keep RL and Gnd not connected, to reduce digital noise.</p> <p>The A0 and A1 pins are for modifying the I2C address.</p> <p><a href="https://i.stack.imgur.com/bYAmf.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/bYAmf.png" alt="DS3502 typical wiring" /></a></p>
93972
|arduino-uno|web-server|uart|esp8266webserver|arduino-iot-cloud|
A peristaltic pump with pH sensor and web based output project
2023-07-28T02:49:57.577
<p>Good day to you all, I am asking here to confirm that my project is feasible. I have low knowledge of Arduino and other components. Please help me in achieving this project.</p> <p>I already have the peristaltic pump and pH sensor working with Arduino uno. Now I want the output of the pH sensor to be displayed in a webpage or web app, In the webpage I will also make a formula on how much volume is released from the peristaltic pump.</p> <p>So there are two things on my webpage output: the acidity of the liquid and the volume released. I want a wireless setup, so I guess I would use ESP32 (notsure)? Now I kind of getting hard on how to put it on a webpage and the important part is, how to pass the data from the arduino to the ESP32?. Any ideas? or things that I would do?</p> <p>OR</p> <p>I would use the ESP32 alone since I have not so many components and I think the ESP32 can cater for the pHsensor (analog signal) and pwm (motor Peristaltic pump). Correct me if I'm wrong. By this, I won't be having problems about the communication to the arduino and esp32 (UART).</p> <p>Additional Info:<br /> Current Set up-<br /> Arduino - controls the pump and pHsensor<br /> ESP32 - Webpage or webserver</p> <p>Is there any way that I could do this with ESP32 alone? so that I won't be having problems with UART.</p> <p>I want to thank you in advance for giving me insights.</p> <p>Update:</p> <p>by this I decided to use ESP32 alone for the whole project. I just need to rewire all. I'm hoping the ESP32 has PWM pins to control the pwm peristaltic pump and pHsensor(analog signal) pins. Please confirm if you know that ESP32 has these pins(for pwm and analog). By the way I'm using the ESP32S where the TXD0 is in pin 35 which is the GPIO1 and the RXD0 is in pin 34 which is the GPIO3. – Johannes Remotigue 2 days ago Delete</p>
<p>Yes. You will need to add a solid state switch or similar to power the motor. The ESP32 has the radio needed to connect to your wifi so that part is already there. The ESP can be configured as a client or server so take your pick. There is a lot published on the web about doing this with code even posted. The device also has a lot of computing power so it could become a stand alone device which reports the results to the web server or works in conjunction with it.</p> <p>All you will need to add is mainly code. This should get you started. Just be cautious as the Arduino is generally 5V and the ESP is 3.3 volt so some voltage translation may be needed and if using 5V modules and/or MOSFETS. If MOSFETs are involved be very careful of the Vgs ratings to be sure it is on with 3V.</p>
93980
|adc|attiny85|digital-analog-conversion|
How to properly read ADC on an ATtiny85?
2023-07-28T23:15:17.710
<p><strong>What I want to do</strong>: attach six buttons to a single input. Each button triggers a different action.</p> <p><strong>How I want to do it</strong>: Use an AD conversion and add a resistor with different values to each button so that you can distinguish between the different input signals<br /> I use these values: 1k, 4.7k, 18k, 22k, 55k, 300k</p> <p>Vcc is stable 3.3v but I also tried it on 5v. I use Vcc as reference value for the ADC.</p> <p><strong>The problem I have</strong>: no matter what I do I always read the same value on the ADC. Connected to GND it reads 0 and on Vcc it reads a value that’s always the same regardless what resistor I actually use.</p> <p>I tried a lot of things I’ve found on the internet but nothing really worked for me. I’m clearly doing something wrong</p> <p>This is the method I call in <code>setup()</code> to initialize the converter on ADC2(pb4)</p> <pre><code>void initADC() { // 8-bit resolution // set ADLAR to 1 to enable the Left-shift result (only bits ADC9..ADC2 are available) // then, only reading ADCH is sufficient for 8-bit results (256 values) ADMUX = (1 &lt;&lt; ADLAR) | // left shift result (0 &lt;&lt; REFS1) | // Sets ref. voltage to VCC, bit 1 (0 &lt;&lt; REFS0) | // Sets ref. voltage to VCC, bit 0 (0 &lt;&lt; MUX3) | // use ADC2 for input (PB4), MUX bit 3 (0 &lt;&lt; MUX2) | // use ADC2 for input (PB4), MUX bit 2 (1 &lt;&lt; MUX1) | // use ADC2 for input (PB4), MUX bit 1 (0 &lt;&lt; MUX0); // use ADC2 for input (PB4), MUX bit 0 ADCSRA = (1 &lt;&lt; ADEN) | // Enable ADC (1 &lt;&lt; ADPS2) | // set prescaler to 64, bit 2 (1 &lt;&lt; ADPS1) | // set prescaler to 64, bit 1 (0 &lt;&lt; ADPS0); // set prescaler to 64, bit 0 } </code></pre> <p>The code is taken from here <a href="https://www.marcelpost.com/wiki/index.php/ATtiny85_ADC" rel="nofollow noreferrer">https://www.marcelpost.com/wiki/index.php/ATtiny85_ADC</a></p> <p>The page seems to be down at the moment so here is an archived version of it <a href="https://web.archive.org/web/20230128091128/https://www.marcelpost.com/wiki/index.php/ATtiny85_ADC" rel="nofollow noreferrer">https://web.archive.org/web/20230128091128/https://www.marcelpost.com/wiki/index.php/ATtiny85_ADC</a></p> <p>In the <code>loop()</code> method I do basically this: Read ADC and then blink an LED <em>n</em> times, based on the read value.</p> <pre><code>ADCSRA |= (1 &lt;&lt; ADSC); // start ADC measurement while (ADCSRA &amp; (1 &lt;&lt; ADSC) ); // wait till conversion complete uint8_t adcValue = ADCH; if (adcValue &gt;= 0 &amp;&amp; adcValue &lt; 32) { blink(1); } else if (adcValue &gt;= 32 &amp;&amp; adcValue &lt; 126) { blink(2); } else if (adcValue &gt;= 126 &amp;&amp; adcValue &lt; 193) { blink(3); } else if (adcValue &gt;= 193 &amp;&amp; adcValue &lt; 227) { blink(4); } else if (adcValue &gt;= 227 &amp;&amp; adcValue &lt; 245) { blink(5); } else if (adcValue &gt;= 245 &amp;&amp; adcValue &lt;= 255) { blink(6); } delay(60000); </code></pre> <p>My breadboard has the resistors going from Vcc to an empty row and I connect a jumperwire from PB4 to one of these resistors and do an external reset of the microcontroller to test my setup. They share GND/Vcc</p> <p>What am I doing wrong? What can I do to <em>debug</em> this?</p> <p>Thanks</p>
<p>Unfortunately <a href="https://arduino.stackexchange.com/users/40318">@jsotola</a> only posted their solution as a comment. But it was the correct answer. So I'll just post my solution here</p> <p>I now use a voltage divider setup with these values:</p> <p>Voltage divider formula <code>Vs * R2 / (R1 + R2)</code></p> <p>Vs: 3.3v<br /> R2: 100k Ohm<br /> R1: 10k (3.0v), 27k (2.8v), 38k (2.6v), 50k (2.2v), 65k (2.0v)</p> <p>Using an 8-bit ADC, I came up with these <em>if</em> statements to distinguish between the inputs. I gave it some room for deviation</p> <pre><code>if (adcValue &gt;= 227 &amp;&amp; adcValue &lt;= 237) { // 10k ohm (3.0V -&gt; adc 232) } else if (adcValue &gt;= 212 &amp;&amp; adcValue &lt;= 223) { // 18k ohm (2.8V -&gt; adc 217) } else if (adcValue &gt;= 196 &amp;&amp; adcValue &lt;= 206) { // 27k ohm (2.6V -&gt; adc 201) } else if (adcValue &gt;= 181 &amp;&amp; adcValue &lt;= 191) { // 38k ohm (2.4V -&gt; adc 186) } else if (adcValue &gt;= 165 &amp;&amp; adcValue &lt;= 175) { // 50k ohm (2.2V -&gt; adc 170) } else if (adcValue &gt;= 150 &amp;&amp; adcValue &lt;= 160) { // 65k ohm (2.0V -&gt; adc 155) } </code></pre> <p>Here is a picture of my breadboard. I know it's not a real schematic but I couldn't figure that out right now. But I hope it's good enough</p> <p><a href="https://i.stack.imgur.com/xl81z.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/xl81z.jpg" alt="enter image description here" /></a></p>
93982
|arduino-uno|serial|python|
How to fix UnicodeDecodeError when using Serial.println
2023-07-29T10:57:01.737
<p>I am using an Arduino Uno R3 to send instructions to a serial monitor in a Python program with Serial.println. But when I send a specific line, I get a a <code>UnicodeDecodeError</code>.</p> <p>The line in the Arduino code that causes this error is:</p> <pre><code>Serial.println(&quot;Press '1,2,3,4,5' to run motor at 10%, 20%, 30%, 40%, 50% for 2 seconds&quot;); </code></pre> <p>My Python code to read the serial data is:</p> <pre><code>def get_serial_data(self): while 1: try: serial_data = self.serial_connection.readline().decode('Ascii') filtered_serial_data = serial_data.strip('\r\n') self.serial_monitor.insert(END, filtered_serial_data) except TypeError: pass </code></pre> <p>and is called from a thread:</p> <pre><code>thread1 = threading.Thread(target=self.get_serial_data) thread1.daemon = True thread1.start() </code></pre> <p>But I get the following error:</p> <pre><code>UnicodeDecodeError: 'ascii' codec can't decode byte 0x85 in position 36: ordinal not in range(128) </code></pre> <p>Can anyone help why this is happening or how to fix, I saw a stackoverflow post to use a try, except block to get it to ignore this line, but I want to print it out, and I want to understand why I get this error.</p>
<p>I solved the issue. It was a memory issue not a decoding issue. Because the dynamic memory was mostly used up, it affected the encoding of the data. Reducing the amount of memory my code was using resolved the issue.</p> <p>I also discovered, that <code>Serial.println(&quot;some text&quot;)</code> uses a lot of dynamic memory. So by reducing the amount of text I was encoding helped, but also by wrapping the the text in <code>F()</code>, like this:</p> <pre><code>Serial.println(F(&quot;some text&quot;)) </code></pre> <p>Which stores the string in flash memory not sram. Heres a helpful link on the F function:</p> <p><a href="https://arduinogetstarted.com/faq/what-is-serial.println-f" rel="nofollow noreferrer">https://arduinogetstarted.com/faq/what-is-serial.println-f</a></p>
93983
|arduino-nano|temperature-sensor|ds18b20|temperature|
DS18B20 doesn't work reliably
2023-07-29T11:01:32.977
<p>like discribed in the title my temperature sensor goes to -127 after a few minutes of run time, it works again after a restart, I have already replaced the sensor and I'm using the same code for the temperature which I had used before which has been running flawlessly for almost 6 months now, I really have no clue what I did wrong hopefully someone got an idea.</p> <p>Thank you!</p>
<p>There's a problem with using OneWire and Wire/I2C in one Sketch at once.</p> <p>I believe this is because OneWire takes too long not sure, but this is probably why the temperature reading went to -127 after a while to fix thi.</p> <p>I used an NTC 10K at 20°C. Below you can see code to make the NTC work and how to wire it!</p> <p>Hope this helps!</p> <p>Code:</p> <pre><code>#include &lt;math.h&gt; const int thermistor_output = A1; void setup() { Serial.begin(9600); } void loop() { int thermistor_adc_val; float output_voltage, thermistor_resistance, therm_res_ln, temperature; thermistor_adc_val = analogRead(thermistor_output); output_voltage = ( (thermistor_adc_val * 5.0) / 1023.0 ); thermistor_resistance = ((5 * (10.0 / output_voltage)) - 10); thermistor_resistance = thermistor_resistance * 1000 ; therm_res_ln = log(thermistor_resistance); temperature = (1 / (0.001129148 + (0.000234125 * therm_res_ln) + (0.0000000876741 * therm_res_ln * therm_res_ln * therm_res_ln))); temperature = temperature - 273.15; Serial.print(&quot;Temperature in degree Celsius = &quot;); Serial.print(temperature); Serial.print(&quot;\n&quot;); delay(1000); } </code></pre> <p>Wiring: <a href="https://i.stack.imgur.com/aPGbo.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/aPGbo.png" alt="enter image description here" /></a></p>
93992
|esp32|spi|sd-card|
SD Card Mount Failed with Waveshare ESP32 using Arduino IDE
2023-07-30T14:53:09.680
<p>I'm currently working on a project using an ESP32 (the <a href="https://www.waveshare.com/e-paper-esp32-driver-board.htm" rel="nofollow noreferrer">Waveshare ESP32 Driver Board</a>), and I am trying to read data from an SD card, but consistently getting a &quot;SD Card Mount Failed&quot; error. I am using the <a href="https://www.adafruit.com/product/254" rel="nofollow noreferrer">Adafruit SD card reader breakout board</a> and the Arduino IDE.</p> <p>Here's how I've wired the SD card reader to the ESP32</p> <pre><code>SD card ESP32 ------- ----- 3.3V 3.3V GND GND CLK pin 18 (SCK) DO pin 19 (MISO) DI pin 23 (MOSI) CS pin 5 (SS) </code></pre> <p>And here's the relevant code I'm using to setup and test the SD card:</p> <pre><code>#define SCK 18 #define MISO 19 #define MOSI 23 #define CS 5 int setup_sd_card() { SPIClass spi = SPIClass(VSPI); spi.begin(SCK, MISO, MOSI, CS); if (!SD.begin(CS,spi,80000000)) { Serial.println(&quot;ERROR: SD Card Mount Failed&quot;); return -1; } uint8_t cardType = SD.cardType(); if(cardType == CARD_NONE){ Serial.println(&quot;ERROR: No SD card attached&quot;); return -1; } // Code to print out SD card details... return 1; } </code></pre> <p>I've triple-checked my wiring but the code always fails at <code>if (!SD.begin(CS,spi,80000000))</code>. I've tried 3 different SD cards of different sizes, all formatted to FAT32 (64GB, 256GB, 1024GB)</p> <p>Could the issue be related to the ESP32 not being a stock one because it has some hardware for driving an e-paper screen? Here is the schematic: <a href="https://www.waveshare.com/w/upload/8/80/E-Paper_ESP32_Driver_Board_Schematic.pdf" rel="nofollow noreferrer">https://www.waveshare.com/w/upload/8/80/E-Paper_ESP32_Driver_Board_Schematic.pdf</a></p> <p><a href="https://i.stack.imgur.com/cQCu6.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/cQCu6.jpg" alt="Waveshare ESP32 Schematic" /></a></p> <p>Can anyone suggest what might be the issue or what else I could try to debug this problem? Any help would be greatly appreciated.</p>
<p>There are at least two problems with your code.</p> <p>First I think you have a typo in the frequency. Default frequency is 4 MHz, but your parameter in <code>begin</code> is 80 MHz, which I doubt will work.</p> <p>You initialize the <code>spi</code> object on the stack in the function and then supply it to the SD instance. The <code>spi</code> object on stack will be removed when the function ends and the SD object will crash. It has to be an allocation on heap as <code>SPIClass* spi = new SPIClass(VSPI);</code> or a global variable <code>SPIClass spi(VSPI);</code>.</p> <p>And since you use the default pins of VSPI you can use just <code>spi.begin()</code> without the pin numbers.</p>
94000
|esp32|voltage|stepper-motor|
Unable to control motor with ESP32 using logic level shifter
2023-07-31T16:11:18.277
<p>I am using an ESP32 a TB6600 micro stepper, and a Nema 23 stepper motor, I am trying to control the motor with the esp32 but the TB6600 requires a 5v signal, I tried to fix this by using a logic level converter (specifically <a href="https://rads.stackoverflow.com/amzn/click/com/B07LG646VS" rel="nofollow noreferrer" rel="nofollow noreferrer">this</a>) but when I attempt to control the motor I get a very slight hum out of the motor and no movement.</p> <p>The motor controller and motor both work as I tested it with an Arduino Uno.</p> <pre><code>void setup() { pinMode(15, OUTPUT); pinMode(16, OUTPUT); pinMode(17, OUTPUT); digitalWrite(16, HIGH); } void loop() { digitalWrite(15,LOW); digitalWrite(15,HIGH); digitalWrite(17, HIGH); delay(200); } </code></pre> <p>Picture of Circuit <a href="https://i.stack.imgur.com/3W6yZ.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/3W6yZ.jpg" alt="Arduino circuit" /></a></p> <p>Circuit Diagram <a href="https://i.stack.imgur.com/huZA4.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/huZA4.jpg" alt="Circuit Diagram " /></a></p>
<p>I figured out the problem, the logic level switcher I was using is meant for I2C sensors, and thus was only capable of converting open-drain signals and cannot perform push/pull level translation meaning it was not able to provide a data signal to the micro stepper. I replaced the shifter with a shifter capable of push/pull translation specifically <a href="https://www.sparkfun.com/products/12009" rel="nofollow noreferrer">This</a></p>
94016
|voltage|analogwrite|
When I use AnalogueWrite the voltage doesn't vary properly
2023-08-02T22:38:27.267
<p>I have a project where I want to control a pump, I use an Arduino, connected to a driver L298N and I will connect the pin 5, 6, 7 of the arduino to the pin IN2, IN1, ENA of the driver respectively and the motor will be connected to the output</p> <p>My materiel :</p> <ul> <li>Arduino Uno R3</li> <li>Multimeter</li> <li>Arduino IDE 2.1.1</li> </ul> <p>The issue : When I use the function analogWrite the voltage vary only between two value (0v or 5.5v). The pin used was the Digital pin n°7, noted in the code 7.</p> <p>The code :</p> <pre class="lang-cpp prettyprint-override"><code>#define PUMP_DIR_1 5 #define PUMP_DIR_2 6 #define PUMP_PWM 7 #define INVERTED 0 void setup() { Serial.begin(9600); pinMode(PUMP_PWM, OUTPUT); } void set_pump_speed(int speed){ Serial.print(&quot;Set speed &quot;); Serial.print(speed); Serial.print(&quot;\r\n&quot;); analogWrite(PUMP_PWM, speed); } void loop() { set_pump_speed(255); delay(3000); set_pump_speed(0); delay(3000); set_pump_speed(125); delay(3000); } </code></pre> <p>As output I obtained :</p> <blockquote> <p>00:32:17.184 -&gt; Set speed 0<br /> 00:32:20.175 -&gt; Set speed 125<br /> 00:32:23.178 -&gt; Set speed 255<br /> 00:32:26.182 -&gt; Set speed 0<br /> 00:32:29.197 -&gt; Set speed 125<br /> 00:32:32.201 -&gt; Set speed 255</p> </blockquote> <p>From the mutlimeter I obtained :</p> <blockquote> <p>0v when speed = 0<br /> 0v when speed = 125<br /> 5.5v when speed = 255</p> </blockquote> <p>The arduino is not wired to anything</p>
<p>Pin 7 isn't a PWM pin. Use, say, pin 6 and you will get correct results. The PWM pins are marked with a &quot;~&quot; on the board.</p>
94055
|esp8266|web-server|
Problem with reading MIFARE 13.5Mhz with MFRC522 lib
2023-08-07T16:41:26.020
<p>I'm trying to read the UID of MIFARE 13.5Mhz cards with MFRC522 lib and I have defined the following function for it.</p> <pre><code>void getUID() { if (mfrc522.PICC_IsNewCardPresent() &amp;&amp; mfrc522.PICC_ReadCardSerial()) { Serial.println(&quot;Scanned PICC's UID:&quot;); tag = &quot;&quot;; for (byte i = 0; i &lt; mfrc522.uid.size; i++) { tag.concat(String(mfrc522.uid.uidByte[i] &lt; 0x10 ? &quot; 0&quot; : &quot; &quot;)); tag.concat(String(mfrc522.uid.uidByte[i], HEX)); } tag.toUpperCase(); Serial.println(tag); mfrc522.PICC_HaltA(); // Stop reading } } </code></pre> <p>this function works perfectly fine in void loop() but when I call it in the following web request my esp8266 crashes.</p> <pre><code>controlserver.on(&quot;/searchuid&quot;, HTTP_POST, [](AsyncWebServerRequest *request){ transmit = request-&gt;arg(&quot;idcode&quot;); if (request-&gt;hasArg(&quot;configmodule&quot;)) { File file = SPIFFS.open(&quot;/inputString.txt&quot;, &quot;r&quot;); if (!file) { Serial.println(&quot;Failed to open file&quot;); return; } getID(); delay(500); Serial.println(tag); String content = file.readString(); if (content.indexOf(tag) &gt;= 0) { Serial.println(&quot;Found search string&quot;); } else { Serial.println(&quot;Did not find search string&quot;); } } }); </code></pre> <p>and I cannot understand why, any help will be appreciated.</p>
<p>Under <a href="https://github.com/me-no-dev/ESPAsyncWebServer#important-things-to-remember" rel="nofollow noreferrer">&quot;Important Things To Remember&quot;</a> in the ESPAsyncWebServer README:</p> <blockquote> <p>You can not use yield or delay or any function that uses them inside the callbacks</p> </blockquote> <p>Your code calls <code>delay()</code> in the callback, and calls functions that you cannot know do not call <code>delay()</code> or <code>yield()</code>.</p> <p>You need to rewrite your code to follow the instructions in the web server's documentation.</p>
94080
|arduino-uno|interrupt|
Timer interrupt setup for one second is too slow (~ 4 seconds)
2023-08-11T05:08:05.197
<p>I am trying to use the timer interrupt on an Arduion Uno.</p> <p>Here is a imple example code for displaying a progressive digit on a lcd display, which is updated with timer interupt every second:</p> <pre><code>#include &lt;LCD_I2C.h&gt; LCD_I2C lcd(0x27); volatile bool timerFlag = false; // Timer-Flag (timer-Interrupt) int displayWidth = 16; // display width int digit = 0; // current digit void setup() { lcd.begin(); lcd.backlight(); lcd.setCursor(0, 0); lcd.print(&quot;Initializing...&quot;); noInterrupts(); TCCR1A = 0; TCCR1B = (1 &lt;&lt; CS12) | (1 &lt;&lt; CS10); // set Prescaler to 1024 TCNT1 = 0; OCR1A = 15624; // should be 1 second with a prescaler of 102 TIMSK1 |= (1 &lt;&lt; OCIE1A); // Enable timer interrupt interrupts(); } ISR(TIMER1_COMPA_vect) { timerFlag = true; } void loop() { static int position = 0; char displayString[17]; // +1 null termination if (timerFlag) { lcd.clear(); // clear display // update digit and progress digit = (digit + 1) % 10; position = (position + 1) % (displayWidth + 1); memset(displayString, ' ', displayWidth); displayString[displayWidth] = '\0'; add null termination displayString[position] = '0' + digit; // Character for the current digit // Show updated progress on the display lcd.setCursor(0, 1); lcd.print(displayString); timerFlag = false; } } </code></pre> <p>The values for setting up he inteupt timer 1 for 1 second is arround everywhere. BUt the updates generated by this code is clearly much slower than 1 second, it's more about 4 seconds. So i did a comparison with a delay based version of the same example:</p> <pre><code>#include &lt;LCD_I2C.h&gt; LCD_I2C lcd(0x27); int displayWidth = 16; // display width void setup() { lcd.begin(); lcd.backlight(); lcd.setCursor(0, 0); lcd.print(&quot;Initializing...&quot;); } void loop() { for (int digit = 0; digit &lt; 10; digit++) { char displayString[17]; // +1 null termination int position = digit % (displayWidth + 1); // Update progression memset(displayString, ' ', displayWidth); displayString[displayWidth] = '\0'; // add null termination displayString[position] = '0' + digit; // Character for the current digit // Show updated progress on the display lcd.clear(); // Clear display lcd.setCursor(0, 1); lcd.print(displayString); delay(1000); } } </code></pre> <p>This one works as expected and updates every second.</p> <p>So what is wrong with my interrupt settings?</p>
<p>There is a flag in <code>TCCR1A/B</code> called <code>WGM12</code> which sets the <code>wave generation mode (WGM)</code> to <code>Clear Timer on Compare Match (CTC)</code>. This causes the timer to count up to the value in OCR1A and then automatically reset to 0.</p> <p>This flag was forgotten, so the interrupt simply ignores the setting <code>OCR1A = 15624;</code> and counts through to 65535, which corresponds to the observed factor of about 4. Therefore the setting line for TCCR1B must be changed to</p> <pre><code>TCCR1B = (1 &lt;&lt; WGM12) | (1 &lt;&lt; CS12) | (1 &lt;&lt; CS10); // Set CTC mode and set Prescaler to 1024 </code></pre> <p>Now the interrupt is triggered correctly every second.</p>
94098
|serial|convert|
Make my Arduino (Mega or whatever is better for the task) to be able to read and write `Serial` data to a **rj45** port
2023-08-15T19:59:18.077
<p>I have a Chinese hybrid solar inverter that exposes an <strong>rj45 input</strong> which talks the serial protocol (Baud rate 2400, no parity, 8 bits, 1 stop bit). I need my Arduino (say, Mega or whatever, does not really matter) to talk to it. What would be the best option to connect an Arduino board to the rj45 input such that it would be available as <code>Serial</code> in the code?</p> <p>Basically, I'd like the following piece to code to &quot;just work&quot;:</p> <pre><code> uint8_t query[] = {81, 80, 73, 71, 83, 183, 169, 13}; Serial.write(query, sizeof(query)); // Write some bytes to a device, i.e. send a request. Serial.flush(); while (!Serial.available()); // Wait for device to reply. String str = Serial.readString(); // do someting with `str`... </code></pre> <p>In other words, I am looking for a hardware solution to connect my Arduino board to the rj45 input without introducing an unnecessary complication (if any).</p>
<p>Look up the data sheet for the max232. It is an old chip that does what you need. ARDUINOs serial work at 0 to 5v and the old fashioned standard for serial data works at +-12v. Also, there will be a high low inversion.</p>
94129
|serial|
Lilypad sends corrupted data on Serial
2023-08-20T17:11:27.723
<p>I have an Arduino Lilypad with this simple code where I try to write a simple message to the serial console. The baud rate is set to 9600 both in the code as well as in the serial console and I'm using the <a href="https://www.sparkfun.com/products/10275" rel="nofollow noreferrer">FTDI UART tool</a>. However, the output I'm receiving is corrupted and I'm not sure what could be the cause. Any ideas or suggestions are welcome. Thanks!</p> <pre><code> void setup() { pinMode(LED_BUILTIN, OUTPUT); Serial.begin(9600); } void loop() { digitalWrite(LED_BUILTIN, HIGH); delay(1000); digitalWrite(LED_BUILTIN, LOW); delay(3000); Serial.write(&quot;Hello World&quot;); } </code></pre> <p><a href="https://i.stack.imgur.com/erAtj.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/erAtj.png" alt="enter image description here" /></a></p> <p>Arduino is connected to the FTDI tool as shown here <a href="https://i.stack.imgur.com/axOsO.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/axOsO.png" alt="enter image description here" /></a></p>
<p>It looks like the wrong baud rate. That often results in garbage characters. You said in a comment that halving the baud rate on the Arduino end seemed to synchronize the baud rates, and you could see proper characters.</p> <p>I'm a bit puzzled by that because you were evidently able to upload the sketch in the first place. Therefore the baud rate was correct during the uploading process.</p> <p>Looking in the file <code>boards.txt</code> which you should find somewhere in your Arduino installation, there appear to be a number of Lilypad variants. Perhaps you inadvertently chose the wrong one in the &quot;Board&quot; menu in the IDE?</p> <p>It looks like the correct baud rate was used for the uploading, but the code generated by the compiler (because of settings passed by the IDE) thought that the board was running at half the speed it actually was (so it set the baud rate clocks to run faster), so by reducing the baud rate in the Serial.begin they became in sync.</p> <p>You could just live with the difference, or try experimenting with choosing different Lilypad board types.</p> <p>If the baud rate is wrong, probably the delays will be wrong too, whether or not that matters is up to you.</p>
94155
|i2c|arduino-pro-mini|raspberrypi|
Arduino pulls i2c bus down
2023-08-24T13:54:39.983
<p>I am building an airplane. As a controller I am using a Raspberry pi 4. There are 3 sensors (MPU6050, QMC5883L, BME280) and arduino pro mini connected to the raspberry via i2c. When sending requests to the arduino it pulls the bus to 0 and shuts down(?).</p> <ul> <li><p>First screenshot. On the first search for all devices on the bus, the arduino responds and shuts down, but does not pull the bus to 0. On the second search It responds and pulls the bus to 0.</p> </li> <li><p>Second screenshot. Rebooting the arduino, the SDA line goes up. Repeated runs of the search leads to what is shown in the first screenshot.</p> </li> <li><p>Third screenshot. The arduino generates a PWM signal that is interrupted after a request to i2c.</p> </li> </ul> <p>As a test request I use the i2cdetect command on the Raspberry. Raspberry is connected to the sensor bus through a level converter, because the level of signals from Raspberry is 3.3V, and sensors accept 5 volt logic.</p> <p>There is no bus pull-up to the upper level, it is on the schematic of all sensors used (will it be enough?).</p> <p>The arduino has a simple slave i2c device code, writing to registers the value arrived and output it to other elements (servo drives, motor controller, stepper motor drivers). The Arduino acts as a port expander because the Raspberry has only 2 buses and too few outputs for all the necessary devices</p> <p>Why is the bus falling and how can I fix it?</p> <p>arduino code</p> <pre class="lang-cpp prettyprint-override"><code> #include &lt;Wire.h&gt; #include &lt;Servo.h&gt; #include &lt;Stepper.h&gt; uint16_t servoAngle1 = 90; uint16_t servoAngle2 = 90; uint16_t servoAngle3 = 90; uint16_t servoAngle4 = 90; bool zoomIn = false; bool zoomOut = false; bool focusIn = false; bool focusOut = false; Servo servo1; Servo servo2; Servo servo3; Servo servo4; Servo ESC; Stepper zoomMotor(100, 2, 4, 7, 8); Stepper focusMotor(100, 10, 11, 12, 13); void setup() { Wire.begin(0x23); Wire.onReceive(receiveEvent); servo1.attach(3); servo2.attach(5); servo3.attach(6); servo4.attach(9); ESC.attach(11, 1000, 2000); } void loop() { servo1.write(servoAngle1); servo2.write(servoAngle2); servo3.write(servoAngle3); servo4.write(servoAngle4); ESC.write(0); if (zoomIn) { zoomMotor.step(100); zoomIn = false; } if (zoomOut) { zoomMotor.step(-100); zoomOut = false; } if (focusIn) { focusMotor.step(100); focusIn = false; } if (focusOut) { focusMotor.step(-100); focusOut = false; } } void receiveEvent(int howMany) { if (howMany == 2) { uint8_t action = Wire.read(); uint8_t value = Wire.read(); if (action == 1) { servoAngle1 = value; } if (action == 2) { servoAngle2 = value; } if (action == 3) { servoAngle3 = value; } if (action == 4) { servoAngle4 = value; } if (action == 10) { if (value == 1) { zoomIn = true; } if (value == 2) { zoomOut = true; } } if (action == 11) { if (value == 1) { focusIn = true; } if (value == 2) { focusOut = true; } } } else { while (true) { Wire.read(); } } } </code></pre> <p><strong>Screenshot 1</strong> <a href="https://i.imgur.com/bqCf4FN.png" rel="nofollow noreferrer"><img src="https://i.imgur.com/bqCf4FN.png" alt="screenshot 1" /></a></p> <p><strong>Screenshot 2</strong> <a href="https://i.imgur.com/n0wGO3m.png" rel="nofollow noreferrer"><img src="https://i.imgur.com/n0wGO3m.png" alt="screenshot 2" /></a></p> <p><strong>Screenshot 3</strong> <a href="https://i.imgur.com/ADLoDgB.png" rel="nofollow noreferrer"><img src="https://i.imgur.com/ADLoDgB.png" alt="screenshot 3" /></a></p> <p><strong>and wiring diagram</strong> <a href="https://i.stack.imgur.com/Frk6W.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Frk6W.jpg" alt="wiring diagram" /></a></p>
<p>For I2C to work there needs to be pull-ups on SDA and SCL somewhere (not one for each device). Typically 4.7k resistors or thereabouts would be used.</p> <p>Also you need a bi-directional voltage level translator. An example schematic is:</p> <p><a href="https://i.stack.imgur.com/3fEFX.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/3fEFX.png" alt="Bi-directional level shifter" /></a></p> <p>Image credit: <a href="https://learn.sparkfun.com/tutorials/bi-directional-logic-level-converter-hookup-guide/all" rel="nofollow noreferrer">Sparkfun: Bi-Directional Logic Level Converter Hookup Guide </a></p> <p>This is because I2C devices actively pull SDA and SCL low, however they rely on the pull-up resistors to pull them high. Also this won't work unless the voltage level shifter is bi-directional.</p> <p>For more information see the <a href="https://cdn.sparkfun.com/tutorialimages/BD-LogicLevelConverter/an97055.pdf" rel="nofollow noreferrer">Philips Application Note AN97055 - Bi-directional level shifter for I²C-bus and other systems.</a></p> <p>If you use the level shifter you need pull-up resistors on both the 3.3V part and the 5V part of the circuit (shown as Rp below).</p> <p><a href="https://i.stack.imgur.com/EpUxY.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/EpUxY.png" alt="Philips Application Note AN97055" /></a></p>
94179
|library|
Uploading a Library to the library manager from a Github branch
2023-08-28T04:11:52.927
<p>I am trying to upload a library to the Arduino Library Manager. I know the GitHub - arduino/library-registry: Arduino Library Manager list repository, and I have already read the instructions, but I have a question that I hope someone can explain to me.</p> <p>The project I am working on is multiplatform, and to fulfill all the requirements for multiple platforms, many files are not required for the Arduino compilation process. I work around this because, with the help of GitHub actions, I have automated a workflow that publishes a branch within the project with an adequate file structure that complies with the Arduino library specification.</p> <p>On the library-registry repo, step 7 says: &quot; This should be the URL of the repository home page. For example: <a href="https://github.com/arduino-libraries/Servo%22" rel="nofollow noreferrer">https://github.com/arduino-libraries/Servo&quot;</a> I am wondering if, in this section, I can put the link to the Arduino branch on the project.</p> <p>This would mean to include : <a href="https://github.com/myProfileName/myProjectName/tree/Arduino" rel="nofollow noreferrer">https://github.com/myProfileName/myProjectName/tree/Arduino</a></p> <p>Instead of : <a href="https://github.com/myProfileName/myProjectName" rel="nofollow noreferrer">https://github.com/myProfileName/myProjectName</a></p> <p>With the reasoning that the second URL would contain many files that are not needed in an Arduino environment</p>
<p>No. As stated in <a href="https://github.com/arduino/library-registry#instructions" rel="nofollow noreferrer">the instructions for submitting a library to the Arduino Library Manager registry</a>, the URL must be to the home page of the repository.</p> <p>The way <a href="https://github.com/arduino/libraries-repository-engine" rel="nofollow noreferrer">the Library Manager index generation system</a> works:</p> <ol> <li>Clone the repository from the URL that was registered URL.</li> <li>Check out each <a href="https://git-scm.com/book/en/v2/Git-Basics-Tagging" rel="nofollow noreferrer">Git tag</a> in the repository.</li> <li>Check to see whether the repository contains an Arduino library at that tag.</li> <li>Check to see whether the library release at that tag is already in the index.</li> <li>If it is a valid new library release, add the release to <a href="http://downloads.arduino.cc/libraries/library_index.json" rel="nofollow noreferrer">the index</a>.</li> </ol> <p>So there is no problem with having the Arduino library in a different branches in the repository because the indexer doesn't work from branches. It works from tags, which are independent from branches. You must only make sure to make a Git tag at the commit ref in the Arduino library branch of your repository at the point in the revision history where you make a release of the library.</p> <p>In case you also want to tag other branches, that is fine. Even though tags are the unit of release for Library Manager, the versioning of the library releases is done exclusively using the value of the <code>version</code> field of the <a href="https://arduino.github.io/arduino-cli/latest/library-specification/#library-metadata" rel="nofollow noreferrer"><code>library.properties</code> metadata file</a>. So you can add something to the tag names to differentiate the Arduino library release tags from tags made in other branches (e.g., <code>Arduino-1.2.3</code>, <code>1.2.3</code>).</p> <p>The one consideration with the release strategy I mentioned above is that <a href="https://github.com/arduino/library-registry-submission-parser" rel="nofollow noreferrer">the submission validation system</a> that checks for problems with the library when you <a href="https://github.com/arduino/library-registry#adding-a-library-to-library-manager" rel="nofollow noreferrer">submit</a> it for inclusion in Library Manager checks out <a href="https://github.com/arduino/library-registry-submission-parser/blob/1.1.1/main.go#L349" rel="nofollow noreferrer">the most recent tag</a> in the repository and does that initial validation on the contents of the repository at that specific tag. So you do need to make sure that the Arduino Library release tag is the most recent tag at the time you submit the library.</p> <p>Once the submission is accepted, all tags in the repository will always be processed (ignoring those that don't pass Arduino Library validation), so it won't matter if tags from branches that don't contain an Arduino library are the most recent tags in the repository after the library has been registered.</p>
94188
|arduino-pro-micro|arduinoisp|
Sparkfun Pro Micro (5v) as ISP error
2023-08-28T19:27:09.740
<p>I'm trying to use Sparkfun Pro Micro (5v 16MHz) as ISP to program Attiny chips (OS:Windows10Pro). I followed instructions. Installed proper driver and added Sparkfun boards to ArduinoIDE:</p> <p><a href="https://i.stack.imgur.com/1eUd1.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/1eUd1.png" alt="enter image description here" /></a></p> <p>Using Arduino IDE uploaded ArduinoISP sketch on it. As you can see there are two options available to choose for programmer:</p> <ol> <li>Arduino as ISP</li> <li>Arduino Leonardo/Pro Micro as ISP</li> </ol> <p><a href="https://i.stack.imgur.com/dIhPo.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/dIhPo.png" alt="enter image description here" /></a></p> <p>Which unfortunately both of them give the same error:</p> <pre><code>Sketch uses 28 bytes (2%) of program storage space. Maximum is 1024 bytes. Global variables use 0 bytes (0%) of dynamic memory, leaving 64 bytes for local variables. Maximum is 64 bytes. C:\Users\K1\AppData\Local\Arduino15\packages\MicroCore\tools\avrdude\7.1-arduino.1/bin/avrdude -CC:\Users\K1\AppData\Local\Arduino15\packages\MicroCore\hardware\avr\2.3.0/avrdude.conf -v -pattiny13a -cstk500v1 -PCOM16 -b19200 -Uhfuse:w:0xff:m -Ulfuse:w:0b00111010:m -Uflash:w:C:\Users\K1\AppData\Local\Temp\arduino_build_207900/sketch_aug28a.ino.hex:i avrdude: Version 7.2 Copyright the AVRDUDE authors; see https://github.com/avrdudes/avrdude/blob/main/AUTHORS System wide configuration file is C:\Users\K1\AppData\Local\Arduino15\packages\MicroCore\hardware\avr\2.3.0\avrdude.conf Using Port : COM16 Using Programmer : stk500v1 Overriding Baud Rate : 19200 avrdude stk500_recv() error: programmer is not responding avrdude stk500_getsync() warning: attempt 1 of 10: not in sync: resp=0x00 avrdude stk500_recv() error: programmer is not responding avrdude stk500_getsync() warning: attempt 2 of 10: not in sync: resp=0x00 ... avrdude done. Thank you. the selected serial port does not exist or your board is not connected </code></pre> <p>I tried avrdude in command line with these parameters and got the same results:</p> <pre><code>avrdude -p attiny13a -P COM16 -c avrisp -b 19200 -U flash:w:r.hex -v </code></pre> <p>I also found out that issue most probably has nothing to do with:</p> <ul> <li>Target chip that I'm using: because changing it has no effect</li> <li>Wiring: because even when there is no chip connected to SPI pins of ProMicro I get the same error</li> <li>USB cable is good: I can upload sketches successfully to Pro Micro but cannot use it as ISP and replaced cable to rule that probably out.</li> </ul> <p>This is while in this video the guy does what I want easily and has no issues whatsoever: <a href="https://www.youtube.com/watch?v=7Rz9A9VbDx4" rel="nofollow noreferrer">https://www.youtube.com/watch?v=7Rz9A9VbDx4</a></p> <p>Any ideas appreciated.</p>
<p>GOTCHA... After two days of search and speculation finally found the solution:</p> <p><strong>Short answer:</strong> In avrdude command instead of <strong>-c avrisp</strong> use <strong>-c arduino</strong>:</p> <pre><code>avrdude -p attiny13a -P COM16 -c arduino -b 19200 -U flash:w:r.hex -v </code></pre> <p><strong>Long answer:</strong> My target chip was ATtiny13a, so I had to use MicroCore v2.3.0 which is the only core supporting ATtiny13 for Arduino. Contrary to other cores, in this core's programmers.txt list, each entry should have a <em>upload.protocol</em> line:</p> <pre><code>arduinoasispatmega32u4.upload.protocol= </code></pre> <p>otherwise it will give this error:</p> <pre><code>avrdude programmer_not_found() error: cannot find programmer id {upload.protocol} </code></pre> <p>I have added this line before to make that error go away but apparently with wrong parameter of <strong>stk500v1</strong> that I have imitated from fabric entries! Converting this parameter to <strong>arduino</strong> solved the problem. This is what that entry should look like for ATtiny13 of MicroCore v2.3.0 (\packages\MicroCore\hardware\avr\2.3.0\programmers.txt):</p> <pre><code>arduinoasispatmega32u4.name=Arduino Leo/Micro as ISP arduinoasispatmega32u4.communication=serial arduinoasispatmega32u4.protocol=arduino arduinoasispatmega32u4.upload.protocol=arduino arduinoasispatmega32u4.speed=19200 arduinoasispatmega32u4.program.protocol=arduino arduinoasispatmega32u4.program.speed=19200 arduinoasispatmega32u4.program.tool=avrdude arduinoasispatmega32u4.program.extra_params=-P{serial.port} -b{program.speed} </code></pre> <p>For other cores, like ATTinyCore v1.5.2 (\packages\ATTinyCore\hardware\avr\1.5.2\programmers.txt) no such line is needed hence this entry works fine:</p> <pre><code>arduinoasispatmega32u4.name=Arduino Leo/Micro as ISP arduinoasispatmega32u4.communication=serial arduinoasispatmega32u4.protocol=arduino arduinoasispatmega32u4.speed=19200 arduinoasispatmega32u4.program.protocol=arduino arduinoasispatmega32u4.program.speed=19200 arduinoasispatmega32u4.program.tool=avrdude arduinoasispatmega32u4.program.extra_params=-P{serial.port} -b{program.speed} </code></pre> <p>Also you should update avrdude in the Arduino core manually: Download latest release from <a href="https://github.com/avrdudes/avrdude/releases" rel="nofollow noreferrer">HERE</a>, and replace them IDE's related files. If you can not find them take a look at <a href="https://forum.arduino.cc/t/avrdude-install-location/532406" rel="nofollow noreferrer">HERE</a>. If avrdude is not updated you might get an error like this:</p> <pre><code>Error during upload using programmer The uploader process failed The uploader process failed The uploader returned an error avrdude: Version 6.3-20201216 Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/ Copyright (c) 2007-2014 Joerg Wunsch System wide configuration file is &quot;C:\Users\K1\AppData\Local\arduino15\packages\MicroCore\hardware\avr\2.3.0/avrdude.conf&quot; avrdude: error at C:\Users\K1\AppData\Local\arduino15\packages\MicroCore\hardware\avr\2.3.0/avrdude.conf:421: syntax error avrdude: error reading system wide configuration file &quot;C:\Users\K1\AppData\Local\arduino15\packages\MicroCore\hardware\avr\2.3.0/avrdude.conf&quot; </code></pre> <p><strong>Third Solusion:</strong> Use this App with this configuration: <a href="https://i.stack.imgur.com/9ZyDM.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/9ZyDM.png" alt="enter image description here" /></a></p>
94195
|esp32|spi|lora|
ESP32 TTGO T-Call connect to SX1276
2023-08-29T04:20:51.373
<p>I have an <a href="https://www.lilygo.cc/products/t-call-v1-4" rel="nofollow noreferrer">ESP32 TTGO T-Call</a> and I want to add a LoRa SX1276. I am new to that and I am trying to write a simple program that, when it receives a packet from a LoRa sender, sends via gsm an HTTP request. GSM communication works fine with the TinyGSM library. My problem is the LoRa connection.</p> <p>Specific chips according to <a href="https://github.com/Xinyuan-LilyGO/LilyGo-T-Call-SIM800/issues/49" rel="nofollow noreferrer">this issue</a> have some reserved pins. If I use the pins of <a href="https://randomnerdtutorials.com/ttgo-lora32-sx1276-arduino-ide/" rel="nofollow noreferrer">the above example</a> lora works but GSM does not work, because of the reserved pins for the SIM800. I am posting a piece of code with the LoRa setup that is not working. If there is a need for further explanation please ask. I will appreciate any kind of help.</p> <pre class="lang-cpp prettyprint-override"><code>#define SCK 14 #define SS 15 #define MISO 19 #define MOSI 27 #define RST 34 #define DIO0 33 SPI.begin(SCK, MISO, MOSI, SS); //setup LoRa transceiver module LoRa.setPins(SS, RST, DIO0); while (!LoRa.begin(866E6)) { SerialMonitor.println(&quot;.&quot;); delay(500); } SerialMonitor.println(&quot;LoRa Initializing OK!&quot;); </code></pre> <p><strong>Edited</strong></p> <p>With setting</p> <pre class="lang-c prettyprint-override"><code>#define LORA_MISO 19 #define LORA_MOSI 27 #define LORA_SCK 5 #define LORA_SS 18 #define LORA_RST 14 #define LORA_DIO0 26 </code></pre> <p>Lora works (not sim800) but with the settings of @Juraj comment i am getting</p> <blockquote> <p>E (11571) gpio: GPIO can only be used as input mode [ 11575][E][esp32-hal-gpio.c:130] __pinMode(): GPIO config failed E (11571) gpio: gpio_set_level(226): GPIO output gpio_num error E (11586) gpio: gpio_set_level(226): GPIO output gpio_num error</p> </blockquote> <p><strong>Edit</strong></p> <p>Although the error exists it is working with the above settings:</p> <pre class="lang-c prettyprint-override"><code>#define LORA_MISO 2 #define LORA_MOSI 13 #define LORA_SCK 14 #define LORA_SS 15 #define LORA_RST 34 #define LORA_DIO0 25 </code></pre> <p>Some packets from the sender are lost but it seems to be working. I don't know why, but it is working... Also it does not seem very stable.</p> <p>Finally pins 34-39 can be used as input so <code>#define LORA_RST 34</code> is not working. But it is not receiving yet from the sender.</p>
<p>The issue seems to be arising from the pin definitions and the fact that the SIM800 and the SX1276 LoRa chip on the board might be competing for the same pins, causing interference</p> <p>First, let's understand the TTGO T-Call pin mapping for SIM800:</p> <p>SIM800L IP5306 version 20190610:</p> <ol> <li><strong>4: SIM800L RST</strong></li> <li><strong>23: SIM800L DTR</strong></li> <li><strong>26: SIM800L PWR</strong></li> <li><strong>27: SIM800L TX</strong></li> <li><strong>32: SIM800L RX</strong></li> <li><strong>33: SIM800L RI</strong></li> </ol> <p>From the pins you've listed for the LoRa SX1276:</p> <ol> <li><strong>SCK: 14</strong></li> <li><strong>SS: 15</strong></li> <li><strong>MISO: 19</strong></li> <li><strong>MOSI: 27</strong></li> <li><strong>RST: 34</strong></li> <li><strong>DIO0: 33</strong></li> </ol> <p>It's clear that MOSI on 27 and DIO0 on 33 interfere with SIM800L's pins.</p> <p>You need to select pins for LoRa that do not interfere with the SIM800L. However, <strong>keep in mind that the ESP32 has certain pins that are not suitable for all types of connections.</strong></p> <p>a proposed remapping would be as follows:</p> <pre><code>#define SCK 14 #define SS 15 #define MISO 19 #define MOSI 22 #define RST 34 #define DIO0 25 </code></pre> <p>Tell me if this works.</p>
94199
|arduino-ide|esp32|esp32-s3|
Why Arduino IDE is brignging wrong board name for ESP32 S3
2023-08-29T12:07:54.090
<p><a href="https://i.stack.imgur.com/FaqN7.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/FaqN7.png" alt="enter image description here" /></a></p> <p>I am designing a pcb for ESP32 S3 wroom-1 for testing pins which are safe to use.</p> <p>My PCB look like this:</p> <p><a href="https://i.stack.imgur.com/6zZV9.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/6zZV9.png" alt="enter image description here" /></a></p> <p>I program ESP32 S3 via USB interface gpio19 &quot;D-&quot; gpio20 &quot;D+&quot;. When I plug in my usb, Arduino ide brings wrong name for my Esp32 board. By the way I use USB TYPE C. Everyday it gives different names. Correct one is &quot;ESP32S3 DEV MODULE&quot;.</p> <p><strong>How can I set it to select the correct module automatically on Arduino Ide</strong> as ESP32S3 Dev Module?</p> <p>WRONG 1</p> <p><a href="https://i.stack.imgur.com/V78nw.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/V78nw.png" alt="enter image description here" /></a></p> <p>WRONG 2</p> <p><a href="https://i.stack.imgur.com/YtPrf.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/YtPrf.png" alt="enter image description here" /></a></p> <p>WRONG 3</p> <p><a href="https://i.stack.imgur.com/Gu5kB.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Gu5kB.png" alt="enter image description here" /></a></p> <p>same board different names. interesting</p>
<p>After an Arduino IDE update 2.2, something was solved, yesterday (30,08,2023).</p> <p>There is a new edit button appearing on the board selection menu and then Arduino ide recognises esp32 even after plugging out and in again.</p> <p><a href="https://i.stack.imgur.com/eTPhX.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/eTPhX.png" alt="enter image description here" /></a></p>
94204
|adafruit|tft|
Multiple TFT's not displaying
2023-08-29T22:56:27.220
<p>I am trying to connect about 5 TFT's to my Arduino Uno and I got to the point of hooking two of them up without any issues. However, after a code upload, they stopped working. I then took all the code out and tested each in isolation and they still function. However, together only one of them displays data. The TFT's I am using are the ST7789v2 found here. <a href="https://www.waveshare.com/wiki/1.69inch_LCD_Module#Hardware_Connection_3" rel="nofollow noreferrer">https://www.waveshare.com/wiki/1.69inch_LCD_Module#Hardware_Connection_3</a></p> <p>I have wired them up according to the schematic with &quot;all&quot; pins being shared except the CS pin. Each display has its own.</p> <p>The code looks like this;</p> <pre><code>#include &lt;Adafruit_GFX.h&gt; #include &lt;Adafruit_ST7789.h&gt; #define TFT_CS1 10 #define TFT_CS2 3 #define TFT_RST 8 // Screens shared #define TFT_DC 7 // Screens shared #define TFT_BACKLIGHT 9 // Backlight for all screens Adafruit_ST7789 tftHour1 = Adafruit_ST7789(TFT_CS1, TFT_DC, TFT_RST); Adafruit_ST7789 tftHour2 = Adafruit_ST7789(TFT_CS2, TFT_DC, TFT_RST); Adafruit_ST7789 setupScreen (Adafruit_ST7789 tft){ tft.init(240, 280); tft.fillScreen(ST77XX_BLACK); return tft; } void setup(void) { tftHour1 = setupScreen(tftHour1); tftHour2 = setupScreen(tftHour2); } void loop(){ tftHour1.print(&quot;1&quot;); tftHour2.print(&quot;2&quot;); } </code></pre> <p>When this executes, display 2 shows output but display 1 does not. Weirdly if I take the CS from display 1 and pop it into the same line on the breadboard as CS2, and then put it back into its original position, display 1 and 2 seem to work. But only till the next power cycle or upload.</p> <p>Also oddly, setting the colour of each screen works even if one is blue and the other is say green. Both change to their respective colours. But when I try to write text to them, only one of them has text.</p> <p>If I comment the code for tftHour2, then tftHour1 starts showing text. If I swap the setup code for ftfHour1 and tftHour2, then the display that is last to init, is the one that shows the text and the other stays blank.</p> <p>Like I said, I had all this working and then a simple font change upload and it all stopped working.</p> <p>Any help on this is really appreciated.</p> <p>I should mention that I am a programmer and very new to electronics so please keep it simple.</p> <p>#<strong>Update</strong>. If I have separate RST pins then it works. But I need 5 screen and will run out of pins in that case. Is there a way to get around that?</p>
<p>According to the data sheet, the RST signal is accepted without an active CS, so when sharing this signal, <strong>all</strong> displays are reset if you initialize just one of them. That explains the behavior you observe.</p> <p>You found the solution: Do not share the RST signal in all instances of <code>Adafruit_ST7789</code>.</p> <hr /> <p>Now you worry about the needed number of pins, and that is indeed an issue.</p> <p>One possible solution is to use a decoder that takes <em>n</em> inputs to activate 1 of 2<sup>n</sup> outputs, like this:</p> <p><img src="https://i.stack.imgur.com/5lubu.png" alt="schematic" /></p> <p><sup><a href="/plugins/schematics?image=http%3a%2f%2fi.stack.imgur.com%2f5lubu.png">simulate this circuit</a> &ndash; Schematic created using <a href="https://www.circuitlab.com/" rel="nofollow">CircuitLab</a></sup></p> <p>To control 5 RST lines you will need only 3 pins. Use a binary value to select one of the unused outputs to deactivate all RST lines.</p> <p>The same is true of the CS lines.</p> <p>However, the library in use does not support this kind of control. Therefore, I'm afraid that you need to consider another Arduino model with more pins.</p> <hr /> <p>As a work-around, you might want to try this alternative:</p> <p>Assign the same Arduino pin to all instances of <code>Adafruit_ST7789</code>, as in your first attempt. But do not connect it to the RST inputs of the displays. Leave the Arduino pin unconnected.</p> <p>Instead, use another Arduino pin and connect that to the displays. Then during initialization, reset all displays with your own code. See the data sheet for correct levels and timing.</p> <p>Or try to connect the RST inputs of all displays to VCC, as they may work without an explicit hardware reset just fine.</p> <hr /> <p>In a comment you brought up the idea of using a multiplexer.</p> <p>Without any other change, you would need the selection signals as additional pins to the multiple CS pins, in your case 3 more.</p> <p>Instead you can also share the CS signal in the same way:</p> <p><img src="https://i.stack.imgur.com/CkiYH.png" alt="schematic" /></p> <p><sup><a href="/plugins/schematics?image=http%3a%2f%2fi.stack.imgur.com%2fCkiYH.png">simulate this circuit</a></sup></p> <p>It is very important that you use multiplexers that output the inactive level as required by the displays on not selected outputs!</p> <p>Even now you should instantiate as many <code>Adafruit_ST7789</code> as you have displays, because each instance most probably stores internal information necessary for its correct working. But you can use the same pins on all of them.</p> <p>Before you call any method of an instance, switch the multiplexers to the associated display.</p> <p>To be sure that all data is completely transmitted, you might need a small delay after the called method. Perhaps the called method already blocks until all data is completely transmitted. You might try to read the library's source to learn more.</p>
94212
|programming|json|
How to add one JsonDocument to another in ArduinoJson
2023-08-30T19:51:26.273
<p>I'm utilizing this json library: <a href="https://arduinojson.org/" rel="nofollow noreferrer">https://arduinojson.org/</a></p> <p>I am attempting to write a function that creates a response object, and wraps an already built json document:</p> <pre><code> void sendResponse( ResponseType state, JsonDocument *response ) { DynamicJsonDocument doc(256); doc[F(&quot;state&quot;)] = responseTypeFromEnum(state); doc[F(&quot;response&quot;)] = response; //breaks; how to do? this-&gt;sendJson(&amp;doc); } </code></pre> <p>This fails of course, and I don't see a great solution anywhere...</p> <p>I know I could use <code>createNestedObject()</code>, but this seems to require re-creating the given json object by hand? This would be a sub-optimal case.</p> <p>Is there a way to easily wrap an existing JsonDocument in another?</p> <p>Looking to take</p> <pre><code>{ &quot;some&quot;: &quot;other document&quot; } </code></pre> <p>And wrap it like</p> <pre><code>{ &quot;state&quot;:&quot;OK&quot; &quot;response&quot;: { &quot;some&quot;: &quot;other document&quot; } } </code></pre>
<p>You can add a <a href="https://arduinojson.org/v6/api/jsondocument/" rel="nofollow noreferrer"><code>JsonDocument</code></a> inside another one, but you must pass the document by value, not by pointer. Since you receive a pointer, you need to dereference it before trying to assign:</p> <pre class="lang-cpp prettyprint-override"><code>doc[F(&quot;response&quot;)] = *response; </code></pre> <p><strong>Node 1</strong>: you could avoid this problem by passing <code>response</code> by reference, like so:</p> <pre class="lang-cpp prettyprint-override"><code>void sendResponse(ResponseType state, const JsonDocument &amp;response) { DynamicJsonDocument doc(256); doc[F(&quot;state&quot;)] = responseTypeFromEnum(state); doc[F(&quot;response&quot;)] = response; this-&gt;sendJson(doc); } </code></pre> <p><strong>Node 2</strong>: calling the assignment operator (<code>=</code>) causes a deep copy of the <code>response</code> document. You could avoid this copy by calling <a href="https://arduinojson.org/v6/api/jsonvariant/shallowcopy/" rel="nofollow noreferrer"><code>shallowCopy()</code></a> instead:</p> <pre class="lang-cpp prettyprint-override"><code>doc[F(&quot;response&quot;)].shallowCopy(response); </code></pre> <p><strong>Node 3</strong>: unfortunately <a href="https://arduinojson.org/v6/api/jsonvariant/shallowcopy/" rel="nofollow noreferrer"><code>shallowCopy()</code></a> is unavailable on ArduinoJson 7.</p>
94222
|arduino-ide|uart|
A fatal error occurred: Could not open /dev/ttyUSB0, the port doesn't exist (UART bridge CP2102)
2023-08-31T14:18:59.393
<p>I can't upload my program to ESP32-CAM. It just keeps saying the port doesn't exist. But I can see it in /dev/ttyUSB0 (By the way, I'm on linux, Fedora) The UART bridge is CP2102 Silicon Labs.</p> <p>What I've tried:</p> <ul> <li>Using both IDE 1, 2</li> <li>Removing everything, trying again on IDE 1</li> <li>upgrading permissions</li> </ul> <p>Any help will be appreciated.</p> <hr /> <p><a href="https://i.stack.imgur.com/XwXPK.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/XwXPK.png" alt="enter image description here" /></a> <a href="https://i.stack.imgur.com/z4woLl.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/z4woLl.jpg" alt="enter image description here" /></a></p> <p>After <code>sudo dmesg -wT | grep cp2102</code> as suggested by @timemage, I got this:<a href="https://i.stack.imgur.com/xSKww.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/xSKww.png" alt="enter image description here" /></a></p> <hr />
<p>A <a href="https://www.reddit.com/r/esp32/comments/ybzduf/took_me_1_hour_to_make_a_hello_world/" rel="nofollow noreferrer">post</a> by <a href="https://www.reddit.com/user/Bee_HapBee/" rel="nofollow noreferrer">Bee_HapBee</a> on Reddit solved my issue! Thank you!</p> <pre><code>sudo chmod 666 /dev/ttyUSB0 </code></pre> <blockquote> <p>Yep, I wish esptool.py would've told me that I needed permissions, rather than the port doesn't exist</p> </blockquote>
94224
|esp8266|
How to refresh an iframe in a page made with Espasyncwebserver
2023-08-31T15:31:32.747
<p>So, I have this page on esp8266:</p> <pre class="lang-cpp prettyprint-override"><code> controlserver.on(&quot;/UDEL&quot;, HTTP_GET, [](AsyncWebServerRequest *request){ request-&gt;send(200, &quot;text/html&quot;, htmltd); }); </code></pre> <p><code>htmltd </code> is a string, generated by a function and it contains some forms, and they run in iframe tag,</p> <pre class="lang-html prettyprint-override"><code>&lt;FORM action=&quot;/process&quot; method=&quot;post&quot; id=&quot;config&quot; target=&quot;iframe&quot;&gt; &lt;/form&gt; &lt;iframe style=&quot;visibility: hidden;&quot; src=&quot;http://&quot; )+local_IPstr+&quot;/UDEL&quot; name=&quot;iframe&quot;&gt;&lt;/iframe&gt; </code></pre> <p>and processed by:</p> <pre class="lang-cpp prettyprint-override"><code>controlserver.on(&quot;/process&quot;, HTTP_POST, [](AsyncWebServerRequest *request) { . . . request-&gt;send(200, &quot;text/html&quot;, HTML_CSS_STYLING + &quot;&lt;script&gt;alert(\&quot; Deleted \&quot;)&lt;/script&gt;&quot;); . . . }); </code></pre> <p>They work perfectly fine, and after clicking on submit button the page shows an alert, and it must be reloaded, because the submitted form must be removed from the page. it happens when I reload the page manually. but I want it to happen automatically after each form submission. it tried many ways like :</p> <pre class="lang-html prettyprint-override"><code>&lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;meta charset=&quot;UTF-8&quot; /&gt; &lt;title&gt;Reload iFrame&lt;/title&gt; &lt;/head&gt; &lt;body&gt; &lt;iframe src=&quot;https://www.w3schools.com&quot; id=&quot;myIframe&quot;&gt;&lt;/iframe&gt; &lt;input onclick=&quot;reloadIframe()&quot; type=&quot;button&quot; value=&quot;Click me&quot;&gt; &lt;script&gt; function reloadIframe() { var iframe = document.getElementById(&quot;myIframe&quot;); iframe.contentWindow.location.reload(); } &lt;/script&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>but it doesn't work in esp8266.</p>
<p>From my understanding, your intention is to automatically reload the main page (which contains the form and the iframe) after submitting the form. but the challenge is that the form submits inside the iframe so when you send a response to the iframe, it won't directly impact the main page.</p> <p>I believe you could use a small trick to work this problem around.</p> <p>1- After successfully processing the form data inside the iframe, send back a script that communicates with the parent window (the main page) and instructs it to reload</p> <p>2- In the main page, listen to the received message and then reload.</p> <p>Here is how to implement the proposed solution:</p> <p>On your ESP8266 route handler, send a script in the response to post a message to the parent window after processing the form:</p> <pre class="lang-python prettyprint-override"><code>controlserver.on(&quot;/process&quot;, HTTP_POST, [](AsyncWebServerRequest *request) { //add your processing code String response = HTML_CSS_STYLING + &quot;&lt;script&gt;&quot; &quot;window.parent.postMessage('reloadPage', '*');&quot; &quot;&lt;/script&gt;&quot;; request-&gt;send(200, &quot;text/html&quot;, response); }); </code></pre> <p>window.parent.postMessage will send &quot;reloadPage&quot; string from iframe to parent window. And on your main page (the page that contains the iframe), listen for this message and reload the entire page when the message is received:</p> <pre><code>&lt;FORM action=&quot;/process&quot; method=&quot;post&quot; id=&quot;config&quot; target=&quot;iframe&quot;&gt; &lt;!-- form field here --&gt; &lt;/form&gt; &lt;iframe style=&quot;visibility: hidden;&quot; src=&quot;http://&quot;+local_IPstr+&quot;/UDEL&quot; name=&quot;iframe&quot;&gt;&lt;/iframe&gt; &lt;script&gt; // listen for messages from iframes window.addEventListener('message', function(event) { // Await reloadPage message if(event.data === 'reloadPage') { location.reload(); } }); &lt;/script&gt; </code></pre> <p>Btw instead of using an iframe, you could use AJAX to submit the form so that you get a response directly from the server and refresh the page using <code>location.reload()</code>. This way you can submit form data (or retrieve data) without refreshing the entire page. Only the necessary parts of the page updates.</p> <p>I hope that this helps, if not, please inform me.</p>
94235
|esp32|ethernet|esp32-s3|
Limit of EthernetClient connections
2023-09-01T18:42:05.243
<p>I'm working on a project on which I need to have multiple EthernetClient connections to different servers. All of these connections must be kept alive simultaneously and by this I mean I cannot stop or close one of these clients before starting the other.</p> <p>Currently I can keep 2 simultaneous successful EthernetClient connections. After this, any subsequent client fails to connect to any server. The following code is running on an ESP32-S3 with a W5500 Ethernet module.</p> <pre class="lang-cpp prettyprint-override"><code>#include &lt;Arduino.h&gt; #include &lt;EthernetLarge.h&gt; #include &lt;SPI.h&gt; #define SPI_MOSI 35 #define SPI_MISO 37 #define SPI_SCK 36 #define ETHERNET_CS 38 SPIClass SPI_Ethernet; EthernetClient ethCli1; EthernetClient ethCli2; EthernetClient ethCli3; byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED }; void setup() { Serial0.begin(115200); SPI_Ethernet.begin(SPI_SCK, SPI_MISO, SPI_MOSI, ETHERNET_CS); pinMode(39, OUTPUT); pinMode(47, OUTPUT); digitalWrite(47, HIGH); digitalWrite(39, LOW); delay(500); digitalWrite(39, HIGH); Ethernet.init(ETHERNET_CS); Ethernet.begin(mac); Serial0.println(Ethernet.localIP()); if( !(ethCli1.connect(&quot;httpbin.org&quot;, 80)) ) Serial0.println(&quot;connection &gt; 1 &lt; failed&quot;); else Serial0.println(&quot;connection &gt; 1 &lt; succeeded&quot;); if( !(ethCli2.connect(&quot;httpbin.org&quot;, 80)) ) Serial0.println(&quot;connection &gt; 2 &lt; failed&quot;); else Serial0.println(&quot;connection &gt; 2 &lt; succeeded&quot;); if( !(ethCli3.connect(&quot;httpbin.org&quot;, 80)) ) Serial0.println(&quot;connection &gt; 3 &lt; failed&quot;); else Serial0.println(&quot;connection &gt; 3 &lt; succeeded&quot;); } void loop() { } </code></pre> <p>Which outputs:</p> <pre><code>connection &gt; 1 &lt; succeeded connection &gt; 2 &lt; succeeded connection &gt; 3 &lt; failed </code></pre> <p>In this code I'm using the OPEnSLab-OSU/EthernetLarge Ethernet library. But I also tried to run it with the Ethernet.h with the same output. In the W5500 documentation I was able to find the information that it can keep up to 8 connections open, but I wasn't able to find if the ESP32 has any restrictions like a max of simultaneous connections. Is it possible to keep more than 2 connections alive simultaneously?</p> <p>In short:</p> <ul> <li>I'm using an ESP32-S3 with a W5500 Ethernet Module.</li> <li>I can keep 2 simultaneous connections and closing previous connections before opening a new one works, but in my project I need to keep at least 3 simultaneous connections.</li> <li>Changing from OPEnSLab-OSU/EthernetLarge Ethernet library to Ethernet.h produced the same output.</li> <li>Adding a delay between the connections didn't work.</li> <li>In the example code all the connections are being established to the same server, but in my official project these connections are established to different servers. Either way the output is the same.</li> <li>The W5500 documentation says that it can keep up to 8 simultaneous connections. I wasn't able to find if ESP32 has any restrictions on the limit of simultaneous connections.</li> </ul>
<p>The <code>OPEnSLab-OSU/EthernetLarge</code> library by default defines <code>MAX_SOCK_NUM</code> to <code>2</code>. Increasing this value allowed me to keep more simultaneous connections.</p> <p>Regarding the <code>Ethernet.h</code> library, I also checked it and it was already setting <code>MAX_SOCK_NUM</code> to <code>8</code>. Testing the code again with it also allowed me to keep more simultaneous connections. Why I wasn't able to keep them before when using <code>Ethernet.h</code> it is still a mystery to me.</p>
94237
|arduino-nano|performance|ssd1306|
Arduino Nano is performing really slowly, even though the calculations are simple and there are no delays
2023-09-01T19:58:23.667
<p>I'm working on a tiny ping-pong game based on Arduino Nano. Its modes are &quot;person vs person&quot; and &quot;person vs computer&quot; (the computer just tries to keep its racket at the same Y position as the ball). There are 2 &quot;up&quot; buttons, 2 &quot;down&quot; buttons, two 7-segment score indicators and 2 shift registers controlling them. The display is SSD1306 (128x32 pixels).</p> <p>I'm posting here the entire code because I don't know where the issue lies.</p> <pre class="lang-cpp prettyprint-override"><code>#include &lt;Adafruit_SSD1306.h&gt; // Up/down buttons #define UP1 2 #define DOWN1 3 #define UP2 4 #define DOWN2 5 // Shift registers that control score indicators #define DATA1 6 #define CLOCK1 7 #define LATCH1 8 #define DATA2 9 #define CLOCK2 10 #define LATCH2 11 #define RANDOM_NUMBERS A0 // This port isn't connected to anything and is used to get random seed #define WRAP 118 // Text on display wraps on this position #define SSD1306_ADDRESS 0x3C // I2C address of display Adafruit_SSD1306 ssd1306; const byte numbers[10] = { // Arab numbers for score indicators 0b1111110, 0b0011000, 0b1101101, 0b0111101, 0b0011011, 0b0110111, 0b1110111, 0b0011100, 0b1111111, 0b0111111 }; short currentDirection = -1; short directionState = -1; // The sequence number of next move in the period of ball trajectory short nextMove = -1; short ballX = 63; short ballY = 15; short racket1 = 12; short racket2 = 12; short score1 = 0; short score2 = 0; bool gameOver = false; bool playingWithComputer = false; void setup() { pinMode(UP1, INPUT_PULLUP); pinMode(DOWN1, INPUT_PULLUP); pinMode(UP2, INPUT_PULLUP); pinMode(DOWN2, INPUT_PULLUP); pinMode(DATA1, OUTPUT); pinMode(CLOCK1, OUTPUT); pinMode(LATCH1, OUTPUT); pinMode(DATA2, OUTPUT); pinMode(CLOCK2, OUTPUT); pinMode(LATCH2, OUTPUT); randomSeed(analogRead(RANDOM_NUMBERS)); updateScores(); ssd1306.begin(SSD1306_SWITCHCAPVCC, SSD1306_ADDRESS); ssd1306.display(); delay(2000); // A delay to show the Adafruit logo ssd1306.clearDisplay(); ssd1306.setTextSize(1); ssd1306.setTextColor(WHITE); ssd1306.setCursor(0, 0); // Cursor should be at this position to draw objects correctly printLongText(5, 0, &quot;Press \&quot;up\&quot; to play with computer, otherwise press \&quot;down\&quot;&quot;); while (true) { if (!digitalRead(UP1) || !digitalRead(UP2)) { // Both &quot;up&quot; buttons (as well as both &quot;down&quot; ones) are treated the same unless there's a game &quot;person vs person&quot; playingWithComputer = true; break; } if (!digitalRead(DOWN1) || !digitalRead(DOWN2)) break; delay(5); // This delay is here to avoid overloading the processor } ssd1306.clearDisplay(); ssd1306.display(); delay(100); // This delay is intended to show user that they don't need to hold button any more } void loop() { if (gameOver) { delay(1000); return; } if (nextMove &lt; 0) { pickDirection(); return; } short oldDirection = currentDirection; switch (getBounceType()) { case 0: verticalFlipDirection(); ballY++; break; case 1: verticalFlipDirection(); ballY--; break; case 2: if (ballY &lt; (racket1 - 1) || ballY &gt; (racket1 + 8)) { // This determines if the ball ran shorto the racket or not (true if it did not) score2++; // Ball goes to the center of the screen after goal ballX = 63; ballY = 15; pickDirection(); updateScores(); } else { horizontalFlipDirection(); ballX++; } break; case 3: if (ballY &lt; (racket2 - 1) || ballY &gt; (racket2 + 8)) { score1++; ballX = 63; ballY = 15; pickDirection(); updateScores(); } else { horizontalFlipDirection(); ballX--; } break; case 4: if (racket1 &gt; 1) { score2++; ballX = 63; ballY = 15; pickDirection(); updateScores(); } else { reverseDirection(); // This occurs when the ball rans exactly shorto the corner of its zone ballX++; ballY++; } break; case 5: if (racket2 &gt; 1) { score1++; ballX = 63; ballY = 15; pickDirection(); updateScores(); } else { ballX--; ballY++; reverseDirection(); } break; case 6: if (racket1 &gt; 1) { score2++; ballX = 63; ballY = 15; pickDirection(); updateScores(); } else { reverseDirection(); ballX++; ballY--; } break; case 7: if (racket2 &gt; 1) { score1++; ballX = 63; ballY = 15; pickDirection(); updateScores(); } else { ballX--; ballY--; reverseDirection(); } break; } if (oldDirection != currentDirection) directionState = 0; // Resetting direction state if the ball bounced pickMove(); // Next move may have changed if the ball bounced switch (nextMove) { case 0: ballY--; break; case 1: ballX++; break; case 2: ballY++; break; case 3: ballX--; break; } directionState++; pickMove(); ssd1306.clearDisplay(); ssd1306.drawRect(ballX, ballY, 2, 2, WHITE); if (playingWithComputer) { if (!digitalRead(UP1) || !digitalRead(UP2)) { if (racket1 &gt; 0) racket1--; } if (!digitalRead(DOWN1) || !digitalRead(DOWN2)) { if (racket1 &lt; 24) racket1++; } // This is the algorithm used by computer — it just tries to keep the computer-controlled racket at the same Y position as the ball if ((racket2 + 3) &gt; ballY) { if (racket2 &gt; 0) racket2--; } if ((racket2 + 3) &lt; ballY) { if (racket2 &lt; 24) racket2++; } } else { if (!digitalRead(UP1)) { if (racket1 &gt; 0) racket1--; } if (!digitalRead(DOWN1)) { if (racket1 &lt; 24) racket1++; } if (!digitalRead(UP2)) { if (racket2 &gt; 0) racket2--; } if (!digitalRead(DOWN2)) { if (racket2 &lt; 24) racket2++; } } ssd1306.drawRect(0, racket1, 2, 8, WHITE); ssd1306.drawRect(126, racket2, 2, 8, WHITE); ssd1306.display(); } // This function picks a random direction for the ball void pickDirection() { currentDirection = random(0, 20); directionState = 0; pickMove(); } // This function determines the next move of the ball (up/right/down/left) based on its current direction and direction state void pickMove() { short sector = getSector(); // Directions that go to up-right are in sector 0, those going to down-right are in sector 1, etc switch (currentDirection) { case 0: case 5: case 10: case 15: directionState = directionState % 5; // Resetting direction state when the ball reaches next period of its trajectory // At certain direction states the ball goes to its primary direction (e.g. in an almost vertical trajectory the primary direction would be up) // At other states it goes to the secondary direction, which when added to the primary one forms the actual trajectory of the ball // Sectors divide into 2 parts. The first part includes 3 trajectories which have their primary direction number (up - 0, right - 1, down - 2, left - 3) same as sector number // Secondary directions in first part are sector number plus 1 // In the second part the primary direction is (sector_number + 1) % 4 and the secondary one is the sector number // There are 20 supported trajectories (5 in each of 4 sectors). They are presented in Ping-Pong.png // First trajectories in each sector (as well as second ones etc) have the same structure, so there's only one code block // for handling first trajectories of all sectors. However, their primary and secondary directions differ in each sector // The following line determines if the ball should now go to the primary or secondary direction and based on that sets nextMove nextMove = (directionState == 0 || directionState == 1 || directionState == 3) ? sector : (sector + 1) % 4; return; case 1: case 6: case 11: case 16: directionState = directionState % 4; nextMove = (directionState &lt; 2) ? sector : (sector + 1) % 4; return; case 2: case 7: case 12: case 17: directionState = directionState % 4; nextMove = (directionState == 0 || directionState == 2) ? sector : (sector + 1) % 4; return; case 3: case 8: case 13: case 18: directionState = directionState % 4; nextMove = (directionState &lt; 2) ? getSecondPartMove(sector) : sector; return; case 4: case 9: case 14: case 19: directionState = directionState % 5; nextMove = (directionState == 0 || directionState == 1 || directionState == 3) ? getSecondPartMove(sector) : sector; return; } } // Just a helper for pickMove (determines primary direction of second-part trajectories in a certain sector) short getSecondPartMove(short sector) { return (sector + 1) % 4; } // This function determines the current bounce type (-1 - currently no bounce, 0 - bounce from upper wall, // 1 - bounce from lower wall, 2 - facing the first player's wall, 3 - facing the second player's wall, // 4 - facing upper-left corner, 5 - upper-right corner, 6 - bottom-left, 7 - bottom right // On 4-7 the ball reverses its trajectory short getBounceType() { if (ballX &lt;= 2 &amp;&amp; ballY &lt;= 0) return 4; // Made ballX indents so that the ball bounces from rackets and not bounds of screen if (ballX &gt;= 124 &amp;&amp; ballY &lt;= 0) return 5; if (ballX &lt;= 2 &amp;&amp; ballY &gt;= 30) return 6; if (ballX &gt;= 124 &amp;&amp; ballY &gt;= 30) return 7; if (ballX &lt;= 2) return 2; if (ballX &gt;= 124) return 3; if (ballY &lt;= 0) return 0; if (ballY &gt;= 30) return 1; return -1; } // This function flips the current trajectory of the ball vertically to bounce from the upper/lower wall // (source and flipped trajectories have a relationship that differs in different sectors of the source trajectory, see this function) void verticalFlipDirection() { short sector = getSector(); switch (sector) { case 0: case 1: currentDirection = 9 - currentDirection; return; case 2: case 3: currentDirection = 10 + (9 - (currentDirection - 10)); return; } directionState = 0; } // Same as previous function but the translation is horizontal here // (the relationship between source and flipped trajectories is different) void horizontalFlipDirection() { short sector = getSector(); switch (sector) { case 0: case 3: currentDirection = 19 - currentDirection; return; case 1: case 2: currentDirection = 5 + (9 - (currentDirection - 5)); return; } directionState = 0; } // This function reverses the trajectory of the ball void reverseDirection() { currentDirection = (currentDirection + 10) % 20; directionState = 0; } // This function determines the sector of the current trajectory short getSector() { if (currentDirection &lt; 5) return 0; else if (currentDirection &lt; 10) return 1; else if (currentDirection &lt; 15) return 2; else return 3; } // This function prints text on the display, wrapping it at a certain X position void printLongText(short cursorX, short cursorY, String text) { ssd1306.setCursor(cursorX, cursorY); int16_t x, y; uint16_t w, h; short lastSpace = -1; short i; // Adding character by character to current line until the wrapping position is reacher // In parallel finding the last space before wrap (it will be where the line breaks) for (i = 0; i &lt; text.length(); i++) { if (text.charAt(i) == ' ') lastSpace = i; ssd1306.getTextBounds(text.substring(0, i + 1), 0, 0, &amp;x, &amp;y, &amp;w, &amp;h); if (x + w &gt; WRAP &amp;&amp; lastSpace &gt;= 0) { ssd1306.println(text.substring(0, lastSpace + 1)); // Wrapping position reached; breaking the current line at the index of last space in it and printing it text = text.substring(lastSpace + 1); i = -1; // Now the same with next line lastSpace = -1; ssd1306.setCursor(cursorX, ssd1306.getCursorY()); } } ssd1306.println(text); // printing the rest of text ssd1306.display(); ssd1306.setCursor(0, 0); // Cursor should be at this position to draw objects correctly } // This function displays the scores on corresponding indicators and checks if the game if over // (i.e. one of the players has a score of 7) void updateScores() { digitalWrite(LATCH1, false); shiftOut(DATA1, CLOCK1, MSBFIRST, numbers[score1]); // Sending the necessary mask to the shift registers digitalWrite(LATCH1, true); digitalWrite(LATCH2, false); shiftOut(DATA2, CLOCK2, MSBFIRST, numbers[score2]); digitalWrite(LATCH2, true); if (score1 &gt;= 7) { ssd1306.clearDisplay(); printLongText(10, 12, &quot;Player 1 wins!&quot;); ssd1306.display(); gameOver = true; } if (score2 &gt;= 7) { ssd1306.clearDisplay(); printLongText(10, 12, &quot;Player 2 wins!&quot;); ssd1306.display(); gameOver = true; } } </code></pre> <p><strong><a href="https://imgur.com/a/4h438v0" rel="nofollow noreferrer">Look</a> how slowly does the ball move, even though a <code>loop</code> iteration doesn't include any <code>delay</code>s at all, and there are no complex calculations.</strong> Conversion to GIF didn't change the speed.</p> <p>My circuit looks like this (it's just a test, so no buttons, just pull-ups, and no score indicators).</p> <p><img src="https://i.stack.imgur.com/w2aek.png" alt="schematic" /></p> <p><sup><a href="/plugins/schematics?image=http%3a%2f%2fi.stack.imgur.com%2fw2aek.png">simulate this circuit</a> &ndash; Schematic created using <a href="https://www.circuitlab.com/" rel="nofollow">CircuitLab</a></sup></p> <p>Answers <a href="https://arduino.stackexchange.com/questions/16103/arduino-code-on-board-runs-really-slow">here</a> didn't help. Changing the I2C clock speed to 400 KHz didn't help either.</p> <p>So — is such slowness caused by the (not very high) complexity of my code? Or is it some kind of glitch? <strong>Please don't suggest using libraries instead of my own moving and bouncing logic.</strong></p>
<p>I put in some timing into your code. As a tip for you and others who may want to time code, here is a simple way of doing that ...</p> <h2>Timer class</h2> <p>Define a timer class as follows:</p> <pre class="lang-c++ prettyprint-override"><code>class timer { unsigned long start; const char sReason [50]; public: // constructor remembers time it was constructed timer (const char * s) { strncpy (sReason, s, sizeof (sReason) - 1); start = micros (); Serial.print (F(&quot;Start: &quot;)); Serial.println (sReason); }; // destructor gets current time, displays difference ~timer () { unsigned long t = micros (); Serial.print (F(&quot;Finish: &quot;)); Serial.print (sReason); Serial.print (F(&quot; = &quot;)); Serial.print (t - start); Serial.println (F(&quot; µs&quot;)); } }; // end of class timer </code></pre> <h2>How to use the timer class</h2> <p>If you want to time &quot;loop&quot; then just put this at the start of it:</p> <pre class="lang-c++ prettyprint-override"><code>void loop() { timer t (&quot;Loop&quot;); ... other code ... } // end of loop </code></pre> <p>The constructor starts timing, and the destructor (when <code>loop</code> is exited) works out the difference and displays it.</p> <p>To time some specific code, make a &quot;block&quot; like this:</p> <pre class="lang-c++ prettyprint-override"><code> { // start of block timer t (&quot;Draw ball&quot;); ssd1306.clearDisplay(); ssd1306.drawRect(ballX, ballY, 2, 2, WHITE); } // end of block </code></pre> <p>Inside the block the timer instance is created, it times what is inside the block, and displays the result after the <code>}</code> is passed.</p> <p>Naturally, for all this to work you need to do a <code>Serial.begin (115200);</code> in <code>setup</code>.</p> <hr /> <h2>Results of timing</h2> <p>I added the above two timing calls, plus for drawing the rackets and updating the display:</p> <pre class="lang-c++ prettyprint-override"><code> { timer t (&quot;Draw rackets&quot;); ssd1306.drawRect(0, racket1, 2, 8, WHITE); ssd1306.drawRect(126, racket2, 2, 8, WHITE); } { timer t (&quot;ssd1306.display&quot;); ssd1306.display(); } </code></pre> <p>The results I got were:</p> <pre><code>Start: Loop Start: Draw ball Finish: Draw ball = 1812 µs Start: Draw rackets Finish: Draw rackets = 1956 µs Start: ssd1306.display Finish: ssd1306.display = 168944 µs Finish: Loop = 178516 µs </code></pre> <p>Clearly, updating the display is taking almost all the time (169 ms each time, which means you will be doing around 5 loops per second).</p> <p>Following on from a suggestion in <a href="https://forums.adafruit.com/viewtopic.php?t=148978" rel="nofollow noreferrer">the Adafruit forum</a> I changed your constructor for ssd1306 to be:</p> <pre class="lang-c++ prettyprint-override"><code>#define SCREEN_WIDTH 128 #define SCREEN_HEIGHT 32 #define OLED_RESET -1 Adafruit_SSD1306 ssd1306(SCREEN_WIDTH, SCREEN_HEIGHT, &amp;Wire, OLED_RESET); </code></pre> <p>Now the timing is:</p> <pre><code>Start: Loop Start: Draw ball Finish: Draw ball = 1780 µs Start: Draw rackets Finish: Draw rackets = 1956 µs Start: ssd1306.display Finish: ssd1306.display = 21192 µs Finish: Loop = 30648 µs </code></pre> <p>So that is around 33 FPS rather than 5 FPS. A big improvement!</p> <hr /> <h2>Further speed improvements</h2> <p>Following on from your edit about changing from I2C to SPI &quot;not making much difference&quot;, the speed difference would indeed be significant. According to <a href="http://www.gammon.com.au/forum/?id=10918" rel="nofollow noreferrer">my page about protocols</a> SPI can be 30 times as fast as I2C (depending on the I2C clock speed) so I suggest that getting the SPI version of that board would indeed give you a significantly faster refresh rate — at least 10 times as fast.</p> <p>You may then need to rework how you show scores but <a href="http://www.gammon.com.au/forum/?id=10892&amp;reply=6#reply6" rel="nofollow noreferrer">bit banged SPI</a> could be an option for the them. The scores hardly need to update all that quickly, and in any case there would be a lot less data. (The screen has 4096 pixels, and the scores would only be a handful of digits).</p> <hr /> <p>From a comment by SNBS:</p> <blockquote> <p>But I noted in my question that changing the I2C clock speed to 400 KHz (which is 4 times as fast as its regular speed) didn't affect the situation at all.</p> </blockquote> <p>Yes, well the default behaviour for the constructor is to use a 400 kHz clock, see the constructor declaration:</p> <pre class="lang-c++ prettyprint-override"><code>Adafruit_SSD1306(uint8_t w, uint8_t h, TwoWire *twi = &amp;Wire, int8_t rst_pin = -1, uint32_t clkDuring = 400000UL, uint32_t clkAfter = 100000UL); </code></pre> <p>The constructor definition saves <code>clkDuring</code> into <code>wireClk</code>.</p> <pre class="lang-c++ prettyprint-override"><code>Adafruit_SSD1306::Adafruit_SSD1306(uint8_t w, uint8_t h, TwoWire *twi, int8_t rst_pin, uint32_t clkDuring, uint32_t clkAfter) : Adafruit_GFX(w, h), spi(NULL), wire(twi ? twi : &amp;Wire), buffer(NULL), mosiPin(-1), clkPin(-1), dcPin(-1), csPin(-1), rstPin(rst_pin) #if ARDUINO &gt;= 157 , wireClk(clkDuring), restoreClk(clkAfter) #endif </code></pre> <p>At the start of the <code>display</code> function it calls TRANSACTION_START</p> <pre class="lang-c++ prettyprint-override"><code>void Adafruit_SSD1306::display(void) { TRANSACTION_START </code></pre> <p>This is a define:</p> <pre class="lang-c++ prettyprint-override"><code>#define TRANSACTION_START \ if (wire) { \ SETWIRECLOCK; \ } else { \ if (spi) { \ SPI_TRANSACTION_START; \ } \ SSD1306_SELECT; \ } ///&lt; Wire, SPI or bitbang transfer setup </code></pre> <p>And <code>SETWIRECLOCK</code> sets the I2C clock speed for you:</p> <pre class="lang-c++ prettyprint-override"><code>#define SETWIRECLOCK wire-&gt;setClock(wireClk) ///&lt; Set before I2C transfer </code></pre>
94248
|esp8266|spiffs|
how to make this code work with spiffs?
2023-09-02T19:20:18.823
<p>So, I have a page to select a txt file from the user's device and save it to SD card:</p> <pre class="lang-html prettyprint-override"><code>&lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;title&gt;File Upload &lt;/title&gt; &lt;/head&gt; &lt;body&gt; &lt;h1&gt;File Upload &lt;/h1&gt; &lt;form method='POST' action='/upload' enctype='multipart/form-data'&gt; &lt;input type='file' name='upload'&gt; &lt;input type='submit' value='Upload'&gt; &lt;/form&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>and here is my esp8266 code for handling the form :</p> <pre class="lang-cpp prettyprint-override"><code> controlserver.on(&quot;/UPL&quot;, HTTP_GET, [](AsyncWebServerRequest *request){ request-&gt;send(200, &quot;text/html&quot;, upl); }); controlserver.on(&quot;/upload&quot;, HTTP_POST, [](AsyncWebServerRequest *request) { request-&gt;send(200); }, handleUpload); void handleUpload(AsyncWebServerRequest *request, String filename, size_t index, uint8_t *data, size_t len, bool final) { String logmessage = &quot;Client:&quot; + request-&gt;client()-&gt;remoteIP().toString() + &quot; &quot; + request-&gt;url(); if (!index) { logmessage = &quot;Upload Start: &quot; + String(filename); request-&gt;_tempFile = SD.open(&quot;/&quot; + filename, &quot;w&quot;); } if (len) { request-&gt;_tempFile.write(data, len); logmessage = &quot;Writing file: &quot; + String(filename) + &quot; index=&quot; + String(index) + &quot; len=&quot; + String(len); } if (final) { logmessage = &quot;Upload Complete: &quot; + String(filename) + &quot;,size: &quot; + String(index + len); request-&gt;_tempFile.close(); request-&gt;redirect(&quot;/&quot;); } } </code></pre> <p>My project is not big and it doesn't require SD card, and esp8266 has 4mb memory, I have tried to replace SD with spiffs, but I wasn't successful. I don't know that if it's possible to directly write the txt file to spiffs, but it will be ok if I could save it to a string the write it to a file in spiffs.</p>
<p>Thanks to <a href="https://arduino.stackexchange.com/questions/81482/esp-32-upload-files-to-spiffs-via-browser">this</a> post, I did solve the problem.</p> <p>Here is the full code, My html code for the upload page, the form is in the tag:</p> <pre class="lang-html prettyprint-override"><code> &lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;title&gt;File Upload Example&lt;/title&gt; &lt;/head&gt; &lt;body&gt; &lt;h1&gt;File Upload Example&lt;/h1&gt; &lt;form method=&quot;POST&quot; action=&quot;/upload&quot; enctype=&quot;multipart/form-data&quot; target=&quot;iframe&quot;&gt;&lt;input type=&quot;file&quot; name=&quot;upload&quot;&gt;&lt;input type=&quot;submit&quot; value=&quot;Upload&quot;&gt; &lt;/form&gt; &lt;iframe style=&quot;visibility: hidden;&quot; src=&quot;http://&quot; )+local_IPstr+&quot;/Usm&quot; name=&quot;iframe&quot;&gt;&lt;/iframe&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>code for ESP:</p> <pre class="lang-cpp prettyprint-override"><code> void handleUpload(AsyncWebServerRequest *request, String filename, size_t index, uint8_t *data, size_t len, bool final){ if (!index) { request-&gt;_tempFile = SPIFFS.open(&quot;/&quot; + filename, &quot;w&quot;); Serial.println(&quot;1&quot;); } if (len) { request-&gt;_tempFile.write(data, len); Serial.println(&quot;2&quot;); } if (final) { Serial.println(&quot;3&quot;); request-&gt;_tempFile.close(); request-&gt;redirect(&quot;/&quot;); } } controlserver.on(&quot;/upload&quot;, HTTP_POST, [](AsyncWebServerRequest *request) { request-&gt;send(200); }, handleUpload); controlserver.on(&quot;/UPL&quot;, HTTP_GET, [](AsyncWebServerRequest *request){ request-&gt;send(200, &quot;text/html&quot;, upl); }); readFile(SPIFFS, &quot;/11.txt&quot;); // show the content of the uploaded file, obviously you should know the name of the uploaded file! </code></pre> <p>you can write a function like this to make sure the file was delivered:</p> <pre class="lang-cpp prettyprint-override"><code> readFile(fs::FS &amp;fs, const char * path){ Serial.printf(&quot;Reading file: %s\r\n&quot;, path); File file = fs.open(path, &quot;r&quot;); if(!file || file.isDirectory()){ Serial.println(&quot;- empty file or failed to open file&quot;); return String(); } Serial.println(&quot;- read from file:&quot;); String fileContent; while(file.available()){ fileContent+=String((char)file.read()); } file.close(); Serial.println(fileContent); } </code></pre>
94253
|arduino-ide|softwareserial|mkr1010wifi|
reading device or board specific properties from the Arduino MKR WiFi 1010 device
2023-09-03T11:38:40.627
<p>How to read programmatically the device specific properties from the Arduino MKR WiFi 1010 chip or board?</p> <p>For example, following properties of the device:</p> <ul> <li>any identification number, that can uniquely identify the physical device, integer or GUID or string or any other, how to read that from the code?</li> <li>SerialNumber of the MRK WiFi 1010 device</li> <li>ModelNumber of the MRK WiFi 1010 device</li> </ul> <p>I have tried to check the documentation and examples, however I couldn't find anything at all.</p>
<p>The IDE shows the serial number so I looked into the SAMD core and found the function which reads the serial number from registers. It is in the CDC.cpp file</p> <pre class="lang-cpp prettyprint-override"><code>uint8_t Serial_::getShortName(char* name) { // from section 9.3.3 of the datasheet #define SERIAL_NUMBER_WORD_0 *(volatile uint32_t*)(0x0080A00C) #define SERIAL_NUMBER_WORD_1 *(volatile uint32_t*)(0x0080A040) #define SERIAL_NUMBER_WORD_2 *(volatile uint32_t*)(0x0080A044) #define SERIAL_NUMBER_WORD_3 *(volatile uint32_t*)(0x0080A048) utox8(SERIAL_NUMBER_WORD_0, &amp;name[0]); utox8(SERIAL_NUMBER_WORD_1, &amp;name[8]); utox8(SERIAL_NUMBER_WORD_2, &amp;name[16]); utox8(SERIAL_NUMBER_WORD_3, &amp;name[24]); return 32; } </code></pre> <p>from <a href="https://ww1.microchip.com/downloads/en/DeviceDoc/SAM_D21_DA1_Family_DataSheet_DS40001882F.pdf" rel="noreferrer">the datasheet of SAMD21</a>:</p> <blockquote> <p>Each device has a unique 128-bit serial number which is a concatenation of four 32-bit words contained at the following addresses:</p> </blockquote> <blockquote> <p>The uniqueness of the serial number is guaranteed only when using all 128 bits</p> </blockquote>
94273
|pwm|
How to control camera lens by Arduino's PWM? What FOCUS A+, FOCUS A- wires means?
2023-09-05T10:31:23.667
<p>I have a camera lens which I want to control by arduino (like this <a href="https://vi.aliexpress.com/item/1005004141070063.html" rel="nofollow noreferrer">https://vi.aliexpress.com/item/1005004141070063.html</a>)</p> <p>I have an info about wires description but I can't understand what focus A+, A-, B+, B- means? I guess I need to send PWM pulses to A and B wires to move focus in straigt and opposite direction but I can't understand what + and - means. Is it just signal and ground?</p> <p><a href="https://i.stack.imgur.com/9mmbG.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/9mmbG.jpg" alt="Manual" /></a></p>
<p>It looks like you will be dealing with bipolar stepper motors. Most likely, A+ and A− are connected to one coil, whereas B+ and B− are connected to the other coil.</p> <p>See the Arduino documentation: <a href="https://docs.arduino.cc/learn/electronics/stepper-motors" rel="nofollow noreferrer">Arduino and Stepper Motor Configurations</a> for instructions on driving this kind of motor.</p>
94275
|esp32|gps|uart|esp32-s3|
Is it possible to use UART0 freely when connecting ESP32 s3 via USB (D+, D-)?
2023-09-05T13:12:59.607
<p>I've designed a test PCB that utilizes an ESP32 S3 and testing pins. During program uploads, I use the USB interface over GPIO20 and GPIO19 as D+ and D-. Everything works fine in this configuration. However, I've encountered an issue where UART0 becomes inactive after using the USB interface. Now, I want to connect the TX pin of a GPS module (NEO 6m) to UART0's RX pin, but I'm unable to do so. It's impractical to run the code as is because when data is received on RX0, it floods the continuous serial screen. I'm looking for a solution to completely disconnect UART0 from the USB interface so that I can use it independently.</p> <p><strong>In Short How I can receive date from UART0 and than Serial.print to Serial monitor over the USB interface?</strong></p> <pre><code>#define RXD2 6 #define TXD2 7 void setup() { // put your setup code here, to run once: Serial.begin(9600); while (!Serial) delay(200); Serial.println(&quot;start GPS...&quot;); Serial2.begin(9600, SERIAL_8N1, RXD2, TXD2); } void loop() { while (Serial.available()) { Serial.print(char(Serial.read())); } } </code></pre> <p><a href="https://i.stack.imgur.com/3S6Hs.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/3S6Hs.png" alt="enter image description here" /></a></p>
<p><code>Serial</code> is 'com' port over USB on esp32 with native USB (and &quot;USB CDC On Boot&quot; option selected in Tools menu). <strong>For UART0 the core then creates <code>Serial0</code>.</strong></p> <p>From <a href="https://docs.espressif.com/projects/arduino-esp32/en/latest/guides/tools_menu.html?highlight=Serial0#usb-cdc-on-boot" rel="nofollow noreferrer">documentation</a>:</p> <blockquote> <p>To use the UART as serial output, you can use Serial0.print(&quot;Hello World!&quot;); instead of Serial.print(&quot;Hello World!&quot;); which will be printed using USB CDC.</p> </blockquote>
94281
|joystick|map|
How can I compensate for a joysticks offset value in neutral position?
2023-09-06T09:53:12.270
<p>I have a joystick that outputs the values 0 - 4095. I want to map these values in this fashion (Yes, the reversed mapping is intended):</p> <pre><code>outputValue = map(inputValue, 4095, 0, -2048, 2047); </code></pre> <p>However, the neutral central position of the joystick is offset, outputting 145 instead of 0.</p> <p>Is there a way to map these values - taking the offset value in account - and still have the output values ranging from -2048 to 2047? I fail to do this with the map() function alone, and could need some help with the specific math involved.</p>
<p>You can only approximate it, you have to sacrifice something.</p> <p>The basic problem is that your input range is asymmetric in respect to the mid point. Let's visualize it this way (with a bit of visual exaggeration):</p> <pre><code>min mid max 0----------------------2193-----4095 </code></pre> <p>Another problem is that the whole range 0..4095 may not be physically reachable by the joystick, so your usable range may actually look like this:</p> <pre><code>min mid max 433---------------2193-------3722 </code></pre> <p>So, to calibrate your joystick, you need to measure the min, mid and max points that you can physically reach with exactly that joystick on the input scale (joysticks are analog devices, so their actual ranges can differ from joystick to joystick and even from axis to axis in the same physical joystick).</p> <p>Now, if you have these numbers (I call those calibration values <code>joy_min</code>, <code>joy_mid</code> and <code>joy_max</code>), you need to <code>map</code> both parts of your range separately:</p> <pre><code>if( joy_input &lt; joy_mid ) { output = map(joy_input, joy_min, joy_mid, -2048, 0); } else { output = map(joy_input, joy_mid, joy_max, 0, 2047); } </code></pre> <p>The downside is that any step in the output may represent a slightly different distance in the movement, depending on whether you are currently lower or higher than the measured midpoint. But I expect that to be negligible.</p> <p>Also, keep in mind that this is only for one axis of the joystick. You may need completely different calibration values for the other axis. In addition, you may want to implement a &quot;dead zone&quot; around the midpoint, i.e. always returning <code>output = 0</code> for <code>joy_mid-10 &lt; joy_input &lt; joy_mid+10</code> or something like that.</p> <p>And as the joystick range may drift (with temperature, age, etc...) and <code>map</code> does not constrain the output range, it might be a good idea to apply a <code>output = constrain(output, -2048, 2047)</code> afterwards.</p> <p>(In my code, I assume that you want to map 0..4095 to -2048..2047 as you say in the text; but in your code, you map 4095..0 to -2048..2047, basically flipping the direction. If that part of your code is correct and the text is not, just swap -2048 with 2047 in my code.)</p>
94284
|arduino-nano|stepper|stepper-motor|
Confusing stepper reaction to increase in delayMicroseconds()
2023-09-06T14:48:48.973
<p>I have been following <a href="https://youtu.be/idVcItHfGS4?si=7FADgMjTdCiBJcJJ" rel="nofollow noreferrer">this tutorial</a> using the same hardware, TB6600 driver, 42HS48-1704A (yes I think its supposed to be 42hs40 but thats not what it says the sticker) stepper but am controlling via a Nano.</p> <p>The code,</p> <pre><code>const int stepPin = 5; const int dirPin = 2; const int enPin = 8; int num_steps = 200; int dt = 1000; void setup() { pinMode(stepPin, OUTPUT); pinMode(dirPin, OUTPUT); pinMode(enPin, OUTPUT); digitalWrite(enPin, LOW); } void loop() { digitalWrite(dirPin, HIGH); // Enables the motor to move in a particular direction for(int x = 0; x &lt; num_steps; x++) { digitalWrite(stepPin, HIGH); delayMicroseconds(dt); digitalWrite(stepPin, LOW); delayMicroseconds(dt); } delay(1000); // One second delay digitalWrite(dirPin, LOW); //Changes the direction of rotation for(int x = 0; x &lt; num_steps; x++) { digitalWrite(stepPin, HIGH); delayMicroseconds(dt); digitalWrite(stepPin, LOW); delayMicroseconds(dt); } delay(1000); } </code></pre> <p>I added <code>dt</code> so I could control the step speed but its not behaving as I thought it would.</p> <p>The original code has <code>dt = 500</code> which needed 15V to run &amp; runs not quite chunky movement but bordering on it &amp; just over 1 revolution when <code>num_steps = 2000</code></p> <p>I changed to <code>dt = 1000</code> &amp; now its got really smooth faster motion &amp; doing quite a few revolutions (too fast for me to count with my eyes) but if reduce <code>num_steps = 200</code> that results in 1 revolution &amp; now only needs 9V to run.</p> <p>So, how come when I increase the delay it runs faster? Is this some kind of clocking/synching issue?</p>
<p>With <code>dt = 500</code> you get one step per millisecond. This is probably too fast for the motor/driver combination. When the driver tries to execute another step, while the previous is not fully executed by the motor shaft (which needs some time due to the shafts inertia), the magnets will misalign and the coil current of the current step will not result in a proper rotation of the shaft. Some of the pulses are aligned enough to the motor shaft position just by chance and can result in a correct step. So the motor skips some of the pulses due to its inertia. Increasing the voltage will increase the force of the motor coils, which drive the shaft. Thus it can overcome the described problems easier (the shaft moving faster by the force of one pulse than before)</p> <p>Increasing to <code>dt = 1000</code> gives the motor enough time to follow each step. You aren't loosing steps because the magnets and coils in the motor always align correctly.</p>
94296
|arduino-uno|
With TIMER1 in CTC mode can't get above ~200khz in arduino UNO runnning @ 16MHZ with no prescaller?
2023-09-08T14:38:02.363
<p>I got the following code, and based on the datasheet the Freq should be <code>clk / 2 * Prescaller * (1 + OCR1A)</code> making it that if I set the OCR1A to 0, I should get something close to <strong>8Mhz</strong>, but the maximum I can get is <strong>~200kHZ</strong>. Can anyone help me understand why?</p> <p>In FAST PWM MODE I can reach those speeds, just wanted to know why i can't in CTC MODE.</p> <pre class="lang-cpp prettyprint-override"><code> void setup() { DDRB |= (1 &lt;&lt; PINB1) ; TCCR1A = 0; TCCR1B = 0; OCR1A = 0; TCCR1B |= (1&lt;&lt;CS10) | (1&lt;&lt;WGM12); TIMSK1 |= (1&lt;&lt;OCIE1A); sei(); } void loop() { } ISR (TIMER1_COMPA_vect){ PORTB ^= 1 &lt;&lt; PINB1; } </code></pre>
<p>I disassembled your program. Below is the code for the ISR. Next to each instruction, I wrote the number of CPU cycles it takes, as a comment:</p> <pre class="lang-lisp prettyprint-override"><code>; Prologue: save some registers to the stack. push r1 ; 2 push r0 ; 2 in r0, 0x3f ; 1 push r0 ; 2 clr r1 ; 1 push r24 ; 2 push r25 ; 2 ; ISR body: PORTB ^= 0x02; in r24, 0x05 ; 1 ldi r25, 0x02 ; 1 eor r24, r25 ; 1 out 0x05, r24 ; 1 ; Epilogue: restore registers and return. pop r25 ; 2 pop r24 ; 2 pop r0 ; 2 out 0x3f, r0 ; 1 pop r0 ; 2 pop r1 ; 2 reti ; 4 </code></pre> <p>I count a total of 31 CPU cycles, most of them spent in the prologue and epilogue. Then, there is some overhead:</p> <ul> <li><p>The CPU always executes at least one instruction of the main program between two interrupts. Given that the main program is in a tight loop containing only two double-cycle instructions, that will take two CPU cycles.</p> </li> <li><p>The CPU takes four cycles to enter interrupt mode: prevent nested interrupts, save the program counter and load the address of the interrupt vector.</p> </li> <li><p>The interrupt vector is a <code>jmp</code> instruction that jumps to the ISR. This takes three cycles.</p> </li> </ul> <p>The minimal interrupt period is then given by this sum:</p> <pre><code> 2 one loop instruction 4 enter interrupt mode 3 jump to ISR 31 execute ISR ──────────────────────── 40 total cycles </code></pre> <p>This takes 2.5 µs, giving an interrupt frequency of 400 kHz. Given that you need two interrupts for a full cycle of the output signal, the maximum you can see on the output is then 200 kHz.</p> <p>You can save 10 CPU cycles by toggling the pin with:</p> <pre class="lang-cpp prettyprint-override"><code> PINB |= 1 &lt;&lt; PINB1; </code></pre> <p>This line compiles to a single double-cycle <code>sbi</code> machine instruction. As this instruction doesn't access any CPU registers, you don't need to save and restore <code>r24</code> and <code>r25</code>. Actually, you don't need to save and restore any register, so you could just remove the prologue, and replace the epilogue by a single <code>reti</code> instruction:</p> <pre class="lang-cpp prettyprint-override"><code>ISR (TIMER1_COMPA_vect, ISR_NAKED) { PINB |= 1 &lt;&lt; PINB1; asm(&quot;reti&quot;); // return from interrupt } </code></pre> <p>This gives an ISR that executes in six cycles, and the total interrupt period can then be as small as 15 cycles. Beware though, that you should not write a naked ISR unless you are absolutely sure that the code within it will not clobber any CPU register, nor the status register.</p> <hr /> <p><strong>Clarification</strong>: On the face of it, the instruction</p> <pre class="lang-cpp prettyprint-override"><code>PINB |= 1 &lt;&lt; PINB1; </code></pre> <p>seems to mean: “Load <code>PINB</code>, do a bitwise OR with <code>0x02</code>, then write the result back to <code>PINB</code>”. This is, however, not how the compiler interprets it. Instead, it takes it to mean “set bit 1 of register <code>PINB</code> to one”. This happens to be a single machine instruction, as <code>PINB</code> is a bit-addressable I/O registers.</p> <p>Yes, the avr-gcc compiler may be a bit peculiar in this respect.</p>
94313
|arduino-uno|imu|magnetometer|
Why am I getting wrong compass heading using magnetometer readings?
2023-09-10T11:22:45.270
<p>I have been trying to calculate the compass heading using the magnetometer in an MPU9250 sensor. But the result is not making sense to me. I am completely new in this and do not have much understanding in how magnetometers work and just trying to find resources in the internet to make it work. I am calculating the <code>atan2</code> of the y and x axis readings of the sensor to find out the angle:</p> <pre><code>float mx = imu.mag_x_ut(); float my = imu.mag_y_ut(); float mz = imu.mag_z_ut(); float heading = atan2(my, mx) * 180 / PI; Serial.print(mx); Serial.print(&quot;,&quot;); Serial.print(my); Serial.print(&quot;,&quot;); Serial.print(mz); Serial.print(&quot;,&quot;); Serial.println(heading); </code></pre> <p>My understanding is that when the <code>x</code> axis of my magnetometer faces the north direction the value of <code>heading</code> should be 0, for east 90, south 180 and then for west 270. But my calculations are nowhere near the expected results. I am not even getting a zero reading in any directon. I am attaching the screenshots of the direction reading :</p> <p>This is when x axis points to north. <a href="https://i.stack.imgur.com/BWiup.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/BWiup.png" alt="x pointed to north" /></a></p> <p>Rotated x axis towards east. <a href="https://i.stack.imgur.com/YybqS.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/YybqS.png" alt="x pointed to east" /></a></p> <p>x towards south. <a href="https://i.stack.imgur.com/98QSn.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/98QSn.png" alt="x pointed to south" /></a></p> <p>x towards west. <a href="https://i.stack.imgur.com/72d62.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/72d62.png" alt="x pointed to west" /></a></p> <p>I have also added the raw readings from the magnetometer represnted by <code>mx</code>, <code>my</code> and <code>mz</code>. Is something wrong with my sensor or there is some misunderstanding from my part.</p> <p>EDIT: Readings after hard iron offset compensation.</p> <p><a href="https://i.stack.imgur.com/W8jot.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/W8jot.png" alt="after hard iron offset" /></a></p>
<p>Consider calibrating your magnetometer. Off the shelf, almost all magnetometers require calibration before making use of their data. The offset (commonly referred to as Hard Iron) and the magnitude (commonly referred to as Soft Iron) need to be found for each of the 3 sensors (X, Y &amp; Z) for individual magnetometers.</p> <p>As there is no accelerometer in this design let us simplify the problem and assume the magnetometer will always be used on a flat surface with its Z axis normal to the surface of the Earth. Let us also assume the X and Y sensors in the magnetometer are perfectly orthogonal to one another.</p> <p>To calibrate the magnetometer remove metal objects from the local vicinity and avoid large metal object such as cars by 10s of meters. Sample the X and Y sensors many times as these sensors point toward and away from north. Find the maximum and minimum X and Y values.</p> <p>Find the offset calibration value by adding the minimum and maximum values then divining by 2. Find the magnitude calibration value by arbitrarily picking one axis and adjusting the magnitude of the other to match. Picking X, we subtract the X minimum from the X maximum to find the X range. We do the same for Y to find the Y range. Then we assume the X magnitude calibration value to be 1 and the Y magnitude calibration value to be x-range divided by y-range.</p> <p>Once calibration is done, to get calibrated X and Y values we subtract the X and Y offset respectively. Then we multiply the offset adjusted Y value by the Y magnitude calibration value.</p> <p>Note, this type of calibrated compass is difficult to carry around by hand because it may not be held level with the surface of the earth. Also, because the inclination of the magnetic field points deeper into the earth the more one travels away from the equator, it will require re-calibration when traveling to a different latitude.</p> <p>Calibration calculations based on data in question:</p> <pre><code>X max to min is 42 to -22 so offset is 10 and range is 64 Y max to min is 120 to 48 so offset is 84 and range is 72 So Y magnitude calibration is 64/72 or 0.889 </code></pre> <p>Data when sensors are pointed East:</p> <pre><code>Y ~48 &amp; X ~11 bearing = atan2(((48 - Y_offset) * Y_magnitude), ((11 - X_offset) * X_magnitude)) bearing = atan2(((48 - 84) * 0.889), ((11 - 10) * 1)) bearing = atan2(((-36) * 0.889), (1 * 1)) bearing = atan2(-32.004, 1) bearing = -1.540 rad = -88.236 degrees </code></pre> <p>If instead of -88.236 degrees the value of approximately 90 degrees is desired, change the sign of the Y sensor as part of the calibration process.</p> <p>The C programming function atan2 is an enhanced form of the math arc tan operation. The C programming function atan2 will calculate to a full 2-Pi circle. To verify how this works <a href="https://www.medcalc.org/manual/atan2-function.php" rel="nofollow noreferrer">use this online atan2 calculator</a>.</p>
94332
|arduino-uno|servo|temperature-sensor|
Arduino Servo with temperature sensor (TMP36)
2023-09-11T19:21:37.623
<p>The essence of the program is to measure the temperature, and if the temperature is higher than 26 degrees, the servo rotates by 45 degrees, and if it's lower, it rotates by 179 degrees. However, a short circuit is occurring. At the moment of the first servo rotation, the temperature jumps to 40 degrees (the temperature is calculated from voltage), and after that, the servo continuously rotates back and forth because the temperature is fluctuating between 40 and 20 degrees. What could be the cause of this issue?</p> <p>My code:</p> <pre><code>#include &lt;Servo.h&gt; Servo myServo; const int sensorPin = A0; const float baselineTemp = 20.0; int angle; void setup() { myServo.attach(9); Serial.begin(9600); } void loop() { int sensorVal = analogRead(sensorPin); Serial.println(&quot;Sensor Value: &quot;); Serial.print(sensorVal); float voltage = (sensorVal/1024.0) * 5.0; Serial.println(&quot;Volts:&quot;); Serial.print(voltage); Serial.println(&quot;Celcius:&quot;); float temperature = (voltage - .5) * 100; Serial.print(temperature); if (temperature &lt; baselineTemp) { myServo.write(179); } else { myServo.write(45); } delay(800); } </code></pre> <p>Output in terminal:</p> <pre><code>sensorVal: 149 Volts:0.73 Celcius:22.75 sensorVal: 192 Volts:0.94 Celcius:43.75 sensorVal: 154 Volts:0.75 Celcius:25.20 sensorVal: 188 Volts:0.92 Celcius:41.80 sensorVal: 150 Volts:0.73 Celcius:23.24 sensorVal: 184 Volts:0.90 Celcius:39.84 sensorVal: 151 </code></pre> <p><a href="https://i.stack.imgur.com/3Sn5O.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/3Sn5O.jpg" alt="Servo from right, tmp from left" /></a></p>
<p>You need to power the servo through a separate power supply. High power devices such as motors etc. should not be powered via the Arduino's regulator. That is surely affecting the analogRead() and therefore also the temperature reading as already noted by @jsotola.</p> <p>Secondly, you need to add some hysteresis here to prevent continuous thrashing when the temperature is around the baseline:</p> <pre><code>if (temperature &lt; baselineTemp) { myServo.write(179); } else { myServo.write(45); } </code></pre> <p>Maybe try something like :</p> <pre><code>if (temperature &lt; baselineTemp - 1.0 ) { myServo.write(179); } elseif (temperature &gt; baselineTemp + 1.0 ) { myServo.write(45); } </code></pre> <p>You could also try adding a capacitor across the power rails of the temperature sensor say 10uF very close to the sensor itself.</p>
94357
|led|
blink a Grove - RGB LED Stick
2023-09-14T08:15:52.527
<p>I am trying to blink a Grove - RGB LED Stick (10 - WS2813 Mini 3535) with this code:</p> <pre><code>#include &quot;FastLED.h&quot; int ledState = LOW; // ledState used to set the LED long previousMillis = 0; // will store last time LED was updated long interval = 1000; // interval at which to blink (milliseconds) #define NUM_LEDS 10 CRGB myLeds[NUM_LEDS]; void setup() { FastLED.addLeds&lt;NEOPIXEL, 4&gt;(myLeds, NUM_LEDS); } void loop() { unsigned long currentMillis = millis(); FastLED.setBrightness(25); if (currentMillis - previousMillis &gt;= interval) { // save the last time you blinked the LED previousMillis = currentMillis; // if the LED is off turn it on and vice-versa: if (ledState == LOW) { for (int i = 0; i &lt; NUM_LEDS; i++) { myLeds[i] = CRGB::White; FastLED.show(); } } else { for (int i = 0; i &lt; NUM_LEDS; i++) { myLeds[i] = CRGB::Black; FastLED.show(); } } } } </code></pre> <p>Any idea why it does not blink?</p> <p>Thanks</p>
<p>In your code, you define the global variable <code>ledState</code> and initialize it to the value &quot;LOW&quot;.</p> <p>In the <code>loop()</code> function, the <code>ledState</code> variable is used to determine the (next) state of the LED once every 1000 milliseconds, like this:</p> <pre><code>... // if the LED is off turn it on and vice-versa: if (ledState == LOW) { for (int i = 0; i &lt; NUM_LEDS; i++) { myLeds[i] = CRGB::White; FastLED.show(); } } else { for (int i = 0; i &lt; NUM_LEDS; i++) { myLeds[i] = CRGB::Black; FastLED.show(); } } ... </code></pre> <p>However, since your code does not change value of <code>ledState</code> to reflect the new state of the LED array, the next time the above <code>if (...)</code> comparison is run, the outcome is the same and the color of the LEDs not be changed.</p> <p>The simplest change to make your LEDs blink as you intended, would be to change the above piece of code to the following:</p> <pre><code>... // if the LED is off turn it on and vice-versa: if (ledState == LOW) { for (int i = 0; i &lt; NUM_LEDS; i++) { myLeds[i] = CRGB::White; FastLED.show(); ledState = HIGH; } } else { for (int i = 0; i &lt; NUM_LEDS; i++) { myLeds[i] = CRGB::Black; FastLED.show(); } ledState = LOW; } ... </code></pre> <p>An alternative (arguably more elegant) solution would be to declare <code>ledState</code> as a boolean (true/false) variable so that you can further simplify your code:</p> <pre><code>#include &quot;FastLED.h&quot; bool ledState = false; // ledState used to set the LED long previousMillis = 0; // will store last time LED was updated long interval = 1000; // interval at which to blink (milliseconds) #define NUM_LEDS 10 CRGB myLeds[NUM_LEDS]; void setup() { FastLED.addLeds&lt;NEOPIXEL, 4&gt;(myLeds, NUM_LEDS); } void loop() { unsigned long currentMillis = millis(); FastLED.setBrightness(25); if (currentMillis - previousMillis &gt;= interval) { // save the last time you blinked the LED previousMillis = currentMillis; // if the LED is off turn it on and vice-versa: if (!ledState) { for (int i = 0; i &lt; NUM_LEDS; i++) { myLeds[i] = CRGB::White; FastLED.show(); } } else { for (int i = 0; i &lt; NUM_LEDS; i++) { myLeds[i] = CRGB::Black; FastLED.show(); } } ledState = !ledState; // make ledState reflect the new LED state } } </code></pre>
94371
|eeprom|
Is the EEPROM the best alternative for store non-volatile values with Arduino?
2023-09-15T20:34:32.327
<p>SD-cards are capable of store values even if it is turned off.</p> <p>I don't know what is the time that a EEPROM can keep a value in it's memory, but of course are better than the volatile memory.</p> <p>There are some others ways of store non-volatile values for arduino?</p> <p>Which of these need hardware built-in and which doesn't?</p> <p>Are the EEPROM the best alternative (in terms of facility, durability, and cost) for store non-volatile values when we talk about Arduinos (or even microcontrollers in general)?</p>
<p>EEPROM on the Atmega328P (such as on the Arduino Uno) holds 1KB (1024 bytes) and has a documented write/erase cycle of 100,000 writes.</p> <p>So, if your application only needs to store 1024 bytes in a non-volatile way, and you do not plan to write more than 100,000 times then that is suitable.</p> <p>The sort of things I would use EEPROM for are remembering settings (eg. fan speed, oven temperature, a password for accessing WiFi, that sort of thing).</p> <p>I also personally use it for &quot;remembering&quot; RFID card codes for access to my house. In my experience, using it for that purpose, it has never &quot;forgotten&quot; a code. According to the datasheet it will retain data for 100 years at 25°C.</p> <p>It is convenient because you don't need any extra hardware.</p> <hr /> <p>Other alternatives are SPI or I2C based external EEPROM, such as NVRAM (non-volatile RAM) which would have larger capacity, but you would need to connect it. That would likely be about 5 wires and somewhere to put the chip. An example of that is <a href="https://learn.adafruit.com/adafruit-i2c-fram-breakout/wiring-and-test" rel="nofollow noreferrer">Adafruit I2C FRAM Breakout</a>.</p> <p><a href="https://i.stack.imgur.com/ohktH.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ohktH.jpg" alt="FRAM breakout board" /></a></p> <hr /> <p>You could use a micro-SD card, which I have used on <a href="https://www.gammon.com.au/forum/?id=12106" rel="nofollow noreferrer">another project</a> to record temperature readings every 15 minutes. This has a lot more capacity than EEPROM, and then you can just take the SD card out and read it in an ordinary PC. This needs extra hardware (eg. a holder for the SD card and possibly voltage-level shifters). However you can buy that for around $20, and it is easy enough to hook up.</p> <p><a href="https://i.stack.imgur.com/5M901.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/5M901.png" alt="Micro SD card breakout board" /></a></p> <hr /> <p>I don't know how SQL got into the discussion under the question, but that is a language (Structured Query Language) and not a piece of hardware.</p> <hr /> <p>Another alternative, if you don't particularly want portability, is to send your data along a connection to your PC, and record the data there. Conceivably WiFi could be used for that.</p> <hr /> <h2>Speed</h2> <p>Speed-wise, I would say EEPROM is the fastest because it is natively inside the chip. Other alternatives required sending messages along wires (I2C, SPI, or maybe USB) to somewhere else and that takes time.</p> <p>Writing is slower than reading, because writing involves using electricity to make a chemical change in the chip (turning a 1-bit into a 0-bit) but it is still quite fast.</p>
94375
|sensors|c++|convert|bytes|
How to get recover numeric data sent by an Arduino in binary
2023-09-16T01:03:46.630
<p>I am a C# dev and these C++ data conversions are killing me.</p> <p>I have an Arduino sending binary data through LoRaWAN to AzureIOT. I am trying to decode my Temp/Humid/Bat payload that I am pulling out of AzureIOT Hub.</p> <p>Here is a sample method I am using in C# to parse the byte array. Once I have parsed it, how do I convert those numbers back to their actual values?</p> <p>Here is the input data on the sensor side:</p> <blockquote> <p>T=74.48</p> <p>RH=45.20</p> <p>BatteryVoltage:3332</p> </blockquote> <p>Thanks. Here is how the data was input:</p> <pre><code>float temperature = readDHTTemperature(); //this method prints T to Serial float humidity = readDHTHumidity(); //this method prints H to Serial uint16_t batteryVoltage = readBattery(true); delay(100); unsigned char *puc; puc = (unsigned char *)(&amp;temperature); appDataSize = 10; appData[0] = puc[0]; appData[1] = puc[1]; appData[2] = puc[2]; appData[3] = puc[3]; puc = (unsigned char *)(&amp;humidity); appData[4] = puc[0]; appData[5] = puc[1]; appData[6] = puc[2]; appData[7] = puc[3]; appData[8] = (uint8_t)(batteryVoltage&gt;&gt;8); appData[9] = (uint8_t)batteryVoltage; </code></pre> <p>Here is the output:</p> <pre><code>private static void BytesToString() { var hexStringFromPayLoad = &quot;MzOYQgAAHEINBA==&quot;; var bytes = Base64Decode(hexStringFromPayLoad); Console.WriteLine($&quot;Temp: {bytes[0]}, {bytes[1]}, {bytes[2]}, {bytes[3]}&quot;); Console.WriteLine($&quot;Humid: {bytes[4]}, {bytes[5]}, {bytes[6]}, {bytes[7]}&quot;); Console.WriteLine($&quot;Bat: {bytes[8]}, {bytes[9]}&quot;); /* Temp: 51, 51, 152, 66 Humid: 0, 0, 28, 66 Bat: 13, 4 */ } </code></pre>
<p>Arduinos use very standard formats for their internal binary representations of data:</p> <ul> <li>integers are in <a href="https://en.wikipedia.org/wiki/Two%27s_complement" rel="nofollow noreferrer">two's complement</a></li> <li>floats follow the <a href="https://en.wikipedia.org/wiki/IEEE_754-1985" rel="nofollow noreferrer">IEEE 754 standard</a></li> <li>both are little-endian.</li> </ul> <p>This is the same as your typical x86_64. The implication is that, once the bytes are in your PC, you do not need to perform any conversion at all. All you need to do is either alias or copy the bytes to the memory locations of the variables that are meant to get the values.</p> <p>Example in plain C:</p> <pre class="lang-c prettyprint-override"><code>uint8_t temperature_bytes[] = { 51, 51, 152, 66 }; float temperature; memcpy(&amp;temperature, temperature_bytes, sizeof temperature); // now `temperature` holds the value 76.1. </code></pre> <p>How you would do this in C# is a question that is out of topic in this site.</p>
94379
|arduino-mega|button|
Turn on by long press of a button?
2023-09-16T09:48:14.493
<p>In my project on Arduino, I want to implement turning on the whole circuit by long press of a button.</p> <p>But at the same time, I want the Arduino to be turned off in standby or sleep mode, but I don't know how to wake it up then.</p> <p>Can you please advise me how this can be realized?</p>
<p>You can use a circuit like this to get close to what you want to achieve.</p> <p><a href="https://i.stack.imgur.com/o5EBg.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/o5EBg.jpg" alt="latching circuit" /></a></p> <p>Found on: <a href="https://forum.arduino.cc/t/switch-microcontroller-on-and-off-with-a-button-and-mofset/1047044" rel="nofollow noreferrer">https://forum.arduino.cc/t/switch-microcontroller-on-and-off-with-a-button-and-mofset/1047044</a></p> <p>It is a latching circuit with the special property that you can use the same button to power up the Arduino and later when the Arduino is running, test the button in code.</p> <p>It works like this. If the Arduino is powered off, pressing the button powers up the Arduino. Your program will immediately (or after a specific chosen interval) switch on D6. This sustains the latch.</p> <p>Now in your code, you can detect the button press and do what you like with it. Maybe power the device off by setting D6 to LOW if the button has been pressed for X ms.</p> <p>If you want the device simply to enter sleep mode on a button press, then you can do that also. However, it gets a bit more complicated because the button then has to be used to wake the device. That means setting a pin change interrupt on pin A0 and then testing A0 on wake up to determine the length of the button press. If it is too short, then you can force the Arduino to resume sleep.</p>
94407
|c++|bit|bitshift|
Why is char being "extended" to an int?
2023-09-19T15:36:37.480
<p>I know I'm missing something so simple here, but I can't figure it out.</p> <p>If I do <code>char letter = 'A';</code> then <code>letter = letter &lt;&lt; 8</code>, letter = 0, as one should expect, since we are shifting the bits &quot;off the shelf&quot; to the left.</p> <p>But, if we do this:</p> <pre><code>char letter = 'A'; void setup() { Serial.begin(9600); int twoBytes = letter &lt;&lt; 8; Serial.println(twoBytes, BIN); } void loop() {} </code></pre> <p>The result is 100000100000000, but why? <code>&lt;&lt;</code> has precedence over <code>=</code>, so it should be bitshifting <code>letter</code> left by 8 first, then assigning that value (which should be 0) to <code>twoBytes</code>.</p>
<p>This is a funny, non-intuitive rule of the C++ language called “integral promotion”. Simply stated, it says that no computation is ever performed on a type smaller than <code>int</code>: anything smaller gets implicitly promoted to <code>int</code> as soon as it appears in an arithmetic or logic expression.</p> <p>See <a href="https://en.cppreference.com/w/cpp/language/implicit_conversion" rel="nofollow noreferrer">Implicit conversions</a> in cppreference.com (warnings: it's hairy).</p>
94414
|variables|
Multiple definition error in STM32CubeIDE
2023-09-20T10:52:50.860
<p>How do global variable declarations work?</p> <p>For example:</p> <p>In file1.c I am defining:</p> <pre class="lang-cpp prettyprint-override"><code>#define volt_add 0x20 uint8_t vol[8]= {0x53, 0x35, 0x05, 0x22, volt_add,0x00,0x00,0x00}; uint16_t EM_vol; </code></pre> <p>I need to use all above variables in <em>file2.c</em>.</p> <p>I tried to define them in the <em>global.h</em> file and included that file in both <em>file1.c</em> and <em>file2.c</em>, but I am getting a multiple definition error, first defined here error.</p> <p>How can I do it?</p>
<p>If you want global variable accessible from everywhere you include global.h, you'll need declaration of that variable in header (declatation only):</p> <pre><code>// globals.h: extern uint8_t vol[8]; </code></pre> <p>Anywhere else you'll #include &quot;global.h&quot;</p> <p>But there must be one cpp or c file with:</p> <pre><code>#include &quot;global.h&quot; uint8_t vol[8]= {0x53, 0x35, 0x05, 0x22, volt_add,0x00,0x00,0x00}; </code></pre> <p>If you make this definition in header or more than one .c file, you'll get multiple definition error.</p> <p>Another way would be make it static and make whole definition in the header, however each compilation unit will be using it's own instance and it won't be visible from other compilation units (compilation unit == every c file compiled into own .o file). This is issue on MCUs and if you even want to write into it, it'll be total mess (although nobody uses const correctness in C)</p>
94418
|esp32|isr|performance|logging|
ESP-IDF logging library slows down ISR processing
2023-09-20T20:41:13.297
<p>I'm hacking a project with ESP32-WROOM module. I'm running some timers with alarms along with some peripherals triggering ISRs. In the ISR routine I'm sending events to a queue, and receiving them in a task. Normally I'm seeing ~50 micros delay between ISR routine and the task.</p> <p>I added the <code>esp_log</code> component for logging to UART. If I call some <code>ESP_LOGx</code> in the task after receiving the queue event, the aforementioned delay grows to 25 millis in some cases (depending on the amount of logging).</p> <p>What's the reason? Does <code>esp_log</code> have longish <code>noInterrupt</code> sections internally? Is there any way to avoid them? Any other remedies?</p> <p>Those delays are quire troublesome because on one hand I need logging to get things working. On other hand those delays turn all the timings upside down...</p> <p>I actually switched to <code>esp_log</code> form hand-rolled logger. In my logger I had a 5k fifo queue for log data. The logging calls would format strings and push them into the queue. A low priority task would pop the data and print it to the UART. It was much better in terms of performance. I switched to <code>esp_log</code> for richer functionality, but ... Going back unless there is a fix.</p>
<p>Since your logger uses the UART, you need to take the transmission time into account.</p> <p>Supposing that you use a 9600 baud line and send about 25 bytes.</p> <p>A single byte has 10 bits on the wire, start bit, data bits, and at least one stop bit. There are more options to the protocol, but this is it basically.</p> <p>Each bit takes 1/9600 seconds, this is the definition of 9600 baud. (Actually, this is oversimplified, but nevertheless a correct number here.) 10 bits of one byte take t_Byte = 10 / 9600 s = 1.042 ms.</p> <p>To send 25 bytes, this sums up to about 25 ms.</p> <p>Lesson learned: do not log directly to UART in a time critical task. You found the common solution by queuing the bytes to send. Just make sure that the queue will not fill up in the long term.</p>
94440
|esp32|time|ntpclient|
(Why is) getLocalTime() on ESP32 taking several seconds to complete successfully
2023-09-23T15:56:29.530
<p>This is a cross-post from <a href="https://github.com/espressif/arduino-esp32/discussions/8653" rel="nofollow noreferrer">https://github.com/espressif/arduino-esp32/discussions/8653</a> as it didn't yield any results there.</p> <p>I noticed that <code>getLocalTime()</code> is consistently taking 5-10+ seconds to complete. So far I haven't been able to find the root cause.</p> <p>I am testing on a ESP32-WROVER-B module. On startup the device first connects to WiFi and then tries to sync time.</p> <pre class="lang-cpp prettyprint-override"><code>boolean initTime() { struct tm timeinfo; log_i(&quot;Synchronizing time.&quot;); // Connect to NTP server with 0 TZ offset, call setTimezone() later configTime(0, 0, &quot;pool.ntp.org&quot;); // getLocalTime uses a default timeout of 5s -&gt; the loop takes at most 3*5s to complete for (int i = 0; i &lt; 3; i++) { if (getLocalTime(&amp;timeinfo)) { log_i(&quot;UTC time: %s.&quot;, getCurrentTimestamp(SYSTEM_TIMESTAMP_FORMAT).c_str()); return true; } } log_e(&quot;Failed to obtain time.&quot;); return false; } </code></pre> <pre><code> ... 10:12:28.118 &gt; [ 3634][I][connectivity.h:17] startWiFi(): ...done. IP: 192.168.0.57, WiFi RSSI: -55. - 10:12:28.118 &gt; [ 3700][I][util.h:25] initTime(): Synchronizing time. | -&gt;10:12:34.025 &gt; [ 11572][I][util.h:37] initTime(): UTC time: 2023-09-19 08:12:34. 10:12:34.037 &gt; [ 11572][I][util.h:60] setTimezone(): Setting timezone to 'CET-1CEST,M3.5.0,M10.5.0/3'. 10:12:34.042 &gt; [ 11574][I][main.cpp:175] syncTime(): Current local time: 2023-09-19 10:12:34 ... </code></pre> <p>In the above example it took ~6s for a &quot;valid&quot; timestamp to become available.</p>
<p>Based on the wording in the question, it appears you are requesting an <a href="https://en.wikipedia.org/wiki/Network_Time_Protocol" rel="nofollow noreferrer">NTP</a> re-synchronizing event often. Perhaps as often as possible. Consider that most Arduino projects request an NTP re-synchronizing event once to set the local <a href="https://en.wikipedia.org/wiki/Real-time_clock" rel="nofollow noreferrer">RTC</a>. Then perhaps once a day to check if the RTC is accurate.</p> <p>Keep in mind that many NTP servers defend them selves from attack by throttling the service from an IP address who utilize them excessively. This quote:</p> <blockquote> <p>The NTP server may throttle traffic, especially for clients making frequent requests.</p> </blockquote> <p>... is from <a href="https://weberblog.net/ntp-filtering-delay-blockage-in-the-internet/" rel="nofollow noreferrer">this web site</a>.</p> <hr /> <p>In case you are not aware, <a href="https://learn.adafruit.com/adafruit-pcf8523-real-time-clock/rtc-with-arduino" rel="nofollow noreferrer">if time is important for your Arduino project, consider adding RTC hardware</a>. This can be set to the the local time just after the NTP re-synchronizing. From that point forward, the local RTC can provide the time. Later, it may be prudent to check the local RTC against the NTP reported time. But this is usually not necessary for days at a time for the vast majority of Arduino projects.</p>
94443
|serial|
Arduino to Arduino communication
2023-09-24T03:17:01.873
<p>When I send data to an Arduino Uno via the serial monitor, the serial data goes down the same USB cable used to program the Arduino. So there must be a device on the Arduino board like a FTDI or USB-capable AVR that drives the <code>RXD</code> pin of the Arduino. So my question is: When I want two Arduino boards to communicate with each other over serial, many tutorials say just connect RX and TX on one Arduino to TX to RX on the other. So how come the device on the board that normally drives the <code>RXD</code> pin doesn't &quot;fight&quot; the other Arduino that is also now driving the <code>RXD</code> line?</p>
<p>Another way to do serial communication between Arduinos is to use the SoftwareSerial library using (digital) pins of your choosing for serial communication between the Arduinos. Incidentally, it avoids interference from your computer under simple serial communication,</p> <blockquote> <p>The SoftwareSerial library allows serial communication on other digital pins of an Arduino board, using software to replicate the functionality (hence the name &quot;SoftwareSerial&quot;). It is possible to have multiple software serial ports with speeds up to 115200 bps. A parameter enables inverted signaling for devices which require that protocol.</p> </blockquote> <p><a href="https://docs.arduino.cc/learn/built-in-libraries/software-serial" rel="nofollow noreferrer">https://docs.arduino.cc/learn/built-in-libraries/software-serial</a></p> <p>It takes just a little preparation and understanding, but not much.</p> <pre><code>#include &lt;SoftwareSerial.h&gt; #define rxPin 10 #define txPin 11 // Set up a new SoftwareSerial object SoftwareSerial mySerial = SoftwareSerial(rxPin, txPin); void setup() { // Define pin modes for TX and RX pinMode(rxPin, INPUT); pinMode(txPin, OUTPUT); // Set the baud rate for the SoftwareSerial object mySerial.begin(9600); } void loop() { if (mySerial.available() &gt; 0) { mySerial.read(); } } </code></pre> <p>In this example (copied from the above/linked article), you would use the <code>mySerial</code> variable to do your Arduino to Arduino communication in the same way as you use the standard serial connection. You would also need to wire the <code>RX</code> and <code>TX</code> pins of one Arduino to the <code>TX</code> and <code>RX</code> pin of the other Arduino, respectively.</p> <p>One of the benefits of learning how to use the SoftwareSerial library is that there are many communication devices that use serial connection, such as Bluetooth modules (HC-05, HC-06, and HM-10 for example), that you can now use with ease. In this case, you can replace the wires I had you add with a Bluetooth module and communication between the 2 Arduinos wirelessly. Or you can instead communicate with a mobile device with the Bluetooth module.</p> <p><a href="https://www.instructables.com/Tutorial-Using-HC06-Bluetooth-to-Serial-Wireless-U-1/" rel="nofollow noreferrer">https://www.instructables.com/Tutorial-Using-HC06-Bluetooth-to-Serial-Wireless-U-1/</a></p> <p>Or you could access the internet with a WiFi module over SoftwareSerial.</p> <p><a href="https://www.taintedbits.com/2017/07/21/arduino-uno-esp8266-software-serial/" rel="nofollow noreferrer">https://www.taintedbits.com/2017/07/21/arduino-uno-esp8266-software-serial/</a></p>
94451
|serial|arduino-mega|python|
Python script cannot connect to serial port
2023-09-25T10:44:22.773
<p>I want to control the LEDs with my hand, for this I used the repository <a href="https://github.com/paveldat/finger_counter/tree/main" rel="nofollow noreferrer">https://github.com/paveldat/finger_counter/tree/main</a>. I want to control the LEDs with my hand, for this I used the repository. To connect to the arduino mega serial port, I use the pyserial library, here is the code to which I pass variables.</p> <pre><code>arduinoData = serial.Serial(&quot;com9&quot;, 9600) arduinoData.write(bytes(str(variable), &quot;utf-8&quot;)) </code></pre> <p>to control the LEDs and process data from the serial port, I wrote the following code in the Arduino IDE:</p> <pre><code>void setup() { Serial.begin(9600); pinMode(3, OUTPUT); pinMode(4, OUTPUT); pinMode(5, OUTPUT); pinMode(6, OUTPUT); pinMode(7, OUTPUT); } void loop() { /* if (Serial.available() &gt; 0){ serialData = Serial.read(); for (int i = 3; i&lt;serialData; i++){ digitalWrite(i, HIGH); } } */ if (Serial.available() &gt; 0){ char serialData = Serial.read(); if (serialData == '3'){ digitalWrite(3, HIGH); } else if (serialData == '4'){ digitalWrite(3, HIGH); digitalWrite(4, HIGH); } else if (serialData == '5'){ digitalWrite(3, HIGH); digitalWrite(4, HIGH); digitalWrite(5, HIGH); } else if (serialData == '6'){ digitalWrite(3, HIGH); digitalWrite(4, HIGH); digitalWrite(5, HIGH); digitalWrite(6, HIGH); } else if (serialData == '7'){ digitalWrite(3, HIGH); digitalWrite(4, HIGH); digitalWrite(5, HIGH); digitalWrite(6, HIGH); digitalWrite(7, HIGH); } else if (serialData == '0'){ digitalWrite(3, LOW); digitalWrite(4, LOW); digitalWrite(5, LOW); digitalWrite(6, LOW); digitalWrite(7, LOW); } //Serial.println(serialData); //digitalWrite(serialData, HIGH); //delay(1000); } } </code></pre> <p>when I run this code without connecting the camera and just pass the values to the serial port, then everything works. However, when I try to run this code together with the camera, the following error occurs:</p> <pre><code>serial.serialutil.SerialException: could not open port 'com9': PermissionError(13, 'Access denied.', None, 5) </code></pre> <p>The camera is a laptop webcam, I have not tested the code with the USB camera, the assumption is that the USB camera will not occupy all serial ports.</p>
<p>The problem with accessing the port is solved, it was busy since I tried to open it every time in a loop that receives an image and displays it on the screen. I took out the code for a cycle, but the LEDs did not start. here is the updated code:</p> <pre><code>import cv2 import time import os import serial import HandTrackingModule as htm wCam, hCam = 640, 480 cap = cv2.VideoCapture(0) cap.set(3, wCam) cap.set(4, hCam) folderPath = &quot;fingers&quot; # name of the folder, where there are images of fingers fingerList = os.listdir(folderPath) # list of image titles in 'fingers' folder overlayList = [] for imgPath in fingerList: image = cv2.imread(f'{folderPath}/{imgPath}') overlayList.append(image) pTime = 0 detector = htm.handDetector(detectionCon=0.75) totalFingers = 0 def arduino_write(totalFingers): arduinoData = serial.Serial(&quot;com9&quot;, 9600) arduinoData.write(bytes(str(totalFingers+2)+&quot;\n&quot;, &quot;utf-8&quot;)) arduinoData.close() while True: sucess, img = cap.read() img = cv2.flip(img, 1) img = detector.findHands(img) lmList, bbox = detector.findPosition(img, draw=False) if lmList: fingersUp = detector.fingersUp() totalFingers = fingersUp.count(1) h, w, c = overlayList[totalFingers].shape img[0:h, 0:w] = overlayList[totalFingers] cTime = time.time() fps = 1/ (cTime-pTime) pTime = cTime cv2.putText(img, f'FPS: {int(fps)}', (400, 70), cv2.FONT_HERSHEY_PLAIN, 3, (255, 0, 0), 3) cv2.rectangle(img, (20, 225), (170, 425), (0, 255, 0), cv2.FILLED) cv2.putText(img, str(totalFingers), (45, 375), cv2.FONT_HERSHEY_PLAIN, 10, (255, 0, 0), 25) arduino_write(totalFingers) cv2.imshow(&quot;Image&quot;, img) if cv2.waitKey(1) &amp; 0xFF == ord('q'): break cap.release() cv2.destroyAllWindows() </code></pre>
94459
|arduino-uno|code-review|
error: expected unqualified-id before 'if' if (send) { but all semicolons are available
2023-09-26T13:00:58.177
<p>I am getting a compilation error: expected unqualified-id before 'if' . Btu I have check all the semicolons . Please help finding my error. The rest of the message error reads</p> <pre><code>C:\Users\jecalderon\Documents\Arduino\Codigo_AS7262_Investigacion_V2\Codigo_AS7262_Investigacion_V2.ino:35:1: error: expected unqualified-id before 'if' if (currentMillis - previousMillis &gt;= interval) { ^~ C:........\Codigo_AS7262_Investigacion_V2.ino:40:1: error: expected unqualified-id before 'if' if (send) { ^~ exit status 1 Compilation error: expected unqualified-id before 'if' </code></pre> <pre><code>#include &lt;Wire.h&gt; #include &quot;Adafruit_AS726x.h&quot; //create the object Adafruit_AS726x ams; //buffer para leer valores en bruto uint16_t sensorValues[AS726x_NUM_CHANNELS]; //buffer para guardar los valores calibrados( no esta siendo utilizado en este codigo) //float calibratedValues[AS726x_NUM_CHANNELS]; unsigned long previousMillis = 0; const long interval = 250; bool send = false; void setup() { Serial.begin(115200); while (!Serial) { // inicializa el pin digital LED_BUILTIN como un output. pinMode(LED_BUILTIN, OUTPUT); //inicia y permite la comunicacion con el sensor if (!ams.begin()) { Serial.println(&quot;could not connect to sensor! Please check your wiring.&quot;); } } } void loop() { //lee la temperatura del sensor //uint8_t temp = ams.readTemperature(); //ams.drvOn(); // descomentar esto si quieres usar el led del sensor para hacer medidas ams.startMeasurement(); //begin a measurement //permite que el sensor lea la data cuando este disponible unsigned long currentMillis = millis(); }; //ams.drvOff(); //descomentar esto si quieres usar el led del sensor para hacer medidas if (currentMillis - previousMillis &gt;= interval) { previousMillis = currentMillis; send = true; } if (send) { //lee los valores! ams.readRawValues(sensorValues); //ams.readCalibratedValues(calibratedValues); //Serial.print(&quot;{&quot;); //Serial.print(&quot;Temp: &quot;); //Serial.print(temp); //Serial.print(&quot;,&quot;); //Serial.print(&quot; Violet: &quot;); Serial.print(sensorValues[AS726x_VIOLET]); Serial.print(&quot;,&quot;); //Serial.print(&quot; Blue: &quot;); Serial.print(sensorValues[AS726x_BLUE]); Serial.print(&quot;,&quot;); //Serial.print(&quot; Green: &quot;); Serial.print(sensorValues[AS726x_GREEN]); Serial.print(&quot;,&quot;); //Serial.print(&quot; Yellow: &quot;); Serial.print(sensorValues[AS726x_YELLOW]); Serial.print(&quot;,&quot;); //Serial.print(&quot; Orange: &quot;); Serial.print(sensorValues[AS726x_ORANGE]); Serial.print(&quot;,&quot;); //Serial.print(&quot; Red: &quot;); Serial.print(sensorValues[AS726x_RED]); //Serial.print(&quot;}&quot;); Serial.println(); send = false; } </code></pre>
<p>Check your braces. Use Control-T to autoformat your code and the error will become apparent.</p> <p>This is your entire loop function. Everything after this is is outside of the function.</p> <pre><code>void loop() { //lee la temperatura del sensor //uint8_t temp = ams.readTemperature(); //ams.drvOn(); // descomentar esto si quieres usar el led del sensor para hacer medidas ams.startMeasurement(); //begin a measurement //permite que el sensor lea la data cuando este disponible unsigned long currentMillis = millis(); }; </code></pre>
94471
|esp8266|arduino-ide|linux|
Can't connect esp8266 via USB to Linux Mint 21.1
2023-09-27T15:41:45.167
<h1>What was my problem</h1> <p>I had a big problem with my esp8266. I couldn't upload anything to it using the Arduino IDE 2.2.1, the ttyUSB port couldn't be found.</p> <p>When I plug my esp8266 into the USB Port, it shows up in the port selection in the Arduino IDE but then disappears imminently.</p> <h2>dmesg | grep ch34</h2> <pre class="lang-bash prettyprint-override"><code>[ 7.286317] usbcore: registered new interface driver ch341 [ 7.286328] usbserial: USB Serial support registered for ch341-uart [ 7.286342] ch341 1-3:1.0: ch341-uart converter detected [ 7.304530] usb 1-3: ch341-uart converter now attached to ttyUSB0 [ 7.804730] usb 1-3: usbfs: interface 0 claimed by ch341 while 'brltty' sets config #1 [ 7.811803] ch341-uart ttyUSB0: ch341-uart converter now disconnected from ttyUSB0 [ 7.811814] ch341 1-3:1.0: device disconnected </code></pre> <p>As shown above, the esp8266 is connecting, but then disconnects.</p>
<h1>The solution</h1> <p><a href="https://www.linux.org/threads/ch340-driver-on-linux-mint.44961/post-204493" rel="nofollow noreferrer">https://www.linux.org/threads/ch340-driver-on-linux-mint.44961/post-204493</a></p> <p><code>sudo apt-get remove -y brltty</code></p> <p>Just remove the brltty package.</p> <h2>What is brltty?</h2> <p><a href="https://brltty.app/" rel="nofollow noreferrer">https://brltty.app/</a> <br> &quot;BRLTTY is a background process (daemon) which provides access to the Linux/Unix console (when in text mode) for a blind person using a refreshable braille display. It drives the braille display, and provides complete screen review functionality. Some speech capability has also been incorporated.&quot;</p> <p>So as long as you don't need the abilty for displaying something on a braille display, you'll good to go wit that solution.</p> <p>I hope, that this will help anyone :D I posted this here, because I was searching for that very long, so it might be useful to have short solution for that.</p>
94484
|sensors|esp32|i2c|
Sparkfun ISL29125 breakout board issue with Arduino IDE with ESP32
2023-09-29T17:30:30.490
<p>I am working on a project where I need to get the RGB light value from surrounding ambient light.</p> <p>For that I am using an ESP32 with a Sparkfun ISL29125 breakout board. I have tried to scan available/connected I2C devices addresses. I'm getting the 0x44 address in the output, which is the address of the ISL29125.</p> <p>But when running the following code, I am not getting any output. I have added the library to the Arduino IDE.</p> <p>I have checked all wire connections. 2 other sensors are connected to the I2C bus.</p> <p>I have connected the pins as follows:</p> <p>GPIO21 (ESP32) -&gt; SDA (ISL29125) GPIO22(ESP32) -&gt; SCL (ISL29125).</p> <p>I'm supplying 3.3v and GND from ESP32.</p> <p>I have scanned the I2C bus and getting the addresses of all connected sensors including the ISL29125.</p> <ul> <li>0X38</li> <li>0X44 (Address of the ISL29125)</li> <li>0X47</li> </ul> <p>Following is the source code.</p> <pre class="lang-c prettyprint-override"><code>#include &lt;Wire.h&gt; #include &lt;SparkFunISL29125.h&gt; SFE_ISL29125 RGB_sensor; void setup() { // Initialize serial communication Serial.begin(115200); Serial.println(&quot;Hello123&quot;); // Initialize the ISL29125 with simple configuration so it starts sampling if (!RGB_sensor.init()) { Serial.println(&quot;Sensor Initialization Problem\n\r&quot;); } } void loop() { Serial.println(&quot;Hello&quot;); // Read sensor values (16 bit integers) unsigned int red = RGB_sensor.readRed(); unsigned int green = RGB_sensor.readGreen(); unsigned int blue = RGB_sensor.readBlue(); // Print out readings, change HEX to DEC if you prefer decimal output Serial.print(&quot;Red: &quot;); Serial.println(red,HEX); Serial.print(&quot;Green: &quot;); Serial.println(green,HEX); Serial.print(&quot;Blue: &quot;); Serial.println(blue,HEX); Serial.println(); delay(2000); } </code></pre> <p>This is the output I am getting</p> <pre><code>[ 4][D][esp32-hal-cpu.c:244] setCpuFrequencyMhz(): PLL: 480 / 2 = 240 Mhz, APB: 80000000 Hz Hello123 [ 21][I][esp32-hal-i2c.c:75] i2cInit(): Initialising I2C Master: sda=21 scl=22 freq=100000 </code></pre> <p>I am not getting any RGB value or the code is getting stuck in the <code>init()</code> method. Can anyone guide me? What can be the problem? What is my mistake?</p>
<p>The library file &quot;SparkFunISL29125.cpp&quot; contains this: <code>Wire.begin();</code> and I guess you want it to contain <code>Wire.begin(21,22)</code> from what you have said in a later comment. Best would be to comment out <code>Wire.begin();</code> in the library and put the corrected version in your sketch. In such a situation I'd suggest copying the .cpp and .h files of the library into the sketch folder. You also have to change this in the sketch: <code>#include &lt;SparkFunISL29125.h&gt;</code> to <code>#include &quot;SparkFunISL29125.h&quot;</code> to address the local copy.</p> <p>Further, the schematic of the SparkFun ILS29125 breakout board shows that the on board I2C pullup resistors are connected via a solder jumper which by default is not bridged. You appear to have done the I2C scan test with two other devices connected and may have &quot;benefitted&quot; from their I2C pullup resistors. If you did the live test with the ILS29125 alone, there may have been no I2C pullup resistors in the circuit.</p> <p><a href="https://i.stack.imgur.com/jiQ4M.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/jiQ4M.png" alt="enter image description here" /></a></p> <p><a href="https://i.stack.imgur.com/dxHuR.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/dxHuR.png" alt="schematic" /></a></p>
94492
|communication|attiny|rf|attiny85|
433MHz RF run away TX burst with ATTiny85 IC
2023-09-30T14:31:26.600
<p>I have recently created a sketch for an ATTiny85.</p> <p>My project consists of:</p> <ul> <li>1x ATTiny85 IC only</li> <li>1x 433MHz RF module =&gt; using data pin <code>2</code></li> <li>2x input digital pins =&gt; using pin <code>3</code> and pin <code>4</code></li> </ul> <p>Running at 16MHz using the ATTiny85 board core from <a href="https://github.com/damellis/attiny" rel="nofollow noreferrer">https://github.com/damellis/attiny</a></p> <p>All running on a 5v 1A 7805 only using <code>24.4mA</code> idle <code>29.5mA</code> when TXing.</p> <p>I have optimized my code a bit and the sketch works as intended. However sometimes the RF 433 module just keeps sending data for a few seconds instead of sending a burst then waiting for my 7 second timeout.</p> <p>I do use the internal pullup resistors on pin 3 and 4.</p> <p>This happens intermittently.. I would like to know if anyone has had a similar problem and knows how to prevent this &quot;<em>runaway transmission</em>&quot;.. Or suggestions code improvements etc.</p> <p>Strangely enough I can get 450m+- line of sight (farm land) distance accurate pings on my sensitive receiver using this cheap module.</p> <p><strong>RF 433 Module</strong></p> <p>I have the one with the SMD coil I have also soldered a 17.3cm LAN wire as antenna.</p> <p><a href="https://i.stack.imgur.com/sa8EZ.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/sa8EZ.jpg" alt="enter image description here" /></a></p> <p><strong>SDR Waterfall</strong></p> <p>I expect a constant burst every 7s.</p> <p><a href="https://i.stack.imgur.com/q8min.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/q8min.jpg" alt="enter image description here" /></a></p> <p><strong>Code</strong></p> <p>The code starts by looping a switch statement over states when an input is H/L or a timer runs out a state is changed.</p> <p>When a trigger state is initiated a for loop copies and concatinates a condenses hex string then the next for loop sends these signals over pin 2.</p> <p>After the signal is sent the state then changes to a timeout to wait before sending a pulse again.</p> <p><em>This is where the problem is.</em></p> <p>Sometimes the signal keeps sending as if the state is stuck for a few seconds but then the timer starts working as expected...</p> <p>The longer 15min timer works fine, it's only the 7s and 9s loops that seem to have this issue.</p> <hr /> <p><strong>Pictures of testing PCB</strong></p> <p><a href="https://i.stack.imgur.com/oNXEj.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/oNXEj.jpg" alt="enter image description here" /></a></p> <p><a href="https://i.stack.imgur.com/RdPnA.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/RdPnA.jpg" alt="enter image description here" /></a></p> <hr /> <p><strong>Full sketch</strong> [<em>updated with suggestions</em>]</p> <pre class="lang-arduino prettyprint-override"><code>#include &lt;stdint.h&gt; #include &lt;avr/io.h&gt; #include &lt;util/delay.h&gt; #define DATA_PIN PB2// digital pin 2 #define ALARM_TRIGGER_PIN PB3// digital pin 3 #define LEARN_PIN PB4// digital pin 4 //15min= 900000 ms //16min = 960000 ms //20min= 500000 ms const unsigned long DELAY_TIME_ZONE_HEARTBEAT = 900000;//15min const unsigned long DELAY_TIME_CHECKALARM_TIMEOUT = 7000;//7sec const unsigned long DELAY_TIME_CHECKLEARN_TIMEOUT = 9000;//9sec unsigned long Delay_Start_Check_Alarm = 0; unsigned long Delay_Start_Heartbeat = 0; unsigned long Delay_Start_Learn = 0; char LEARN[] =&quot;269369a6924d36da6c800&quot;;//condensed hexadecimal signal; learnState/tamper same signal char ALARM[] = &quot;da4da69a4934db69b200&quot;;//condensed hexadecimal signal char HEARTBEAT[] =&quot;1269b4d349269b6d36400&quot;;//condensed hexadecimal signal uint16_t pulse = 1100;//Attiny85 chip needs more of delay time uint8_t i; //custom states enum State { ALARMTIMEOUT, CHECKING, HEARTBEATTIMEOUT, HEARTBEATSEND, LEARNTIMEOUT, LEARNSEND, ALARMSEND }; enum State state; void setup() { DDRB |= (1 &lt;&lt; DATA_PIN);//replaces pinMode(DATA_PIN, OUTPUT); DDRB &amp;= ~(1 &lt;&lt; ALARM_TRIGGER_PIN); //replaces pinMode(ALARM_TRIGGER_PIN, INPUT); DDRB &amp;= ~(1 &lt;&lt; LEARN_PIN); //replaces pinMode(LEARN_PIN, INPUT); PORTB |= (1 &lt;&lt; ALARM_TRIGGER_PIN);//initiate alarm pin pullup PORTB |= (1 &lt;&lt; LEARN_PIN);//initiate learn pin pullup ADCSRA &amp;= ~(1 &lt;&lt; ADEN); //Disable ADC, saves ~230uA Delay_Start_Check_Alarm = Delay_Start_Heartbeat = Delay_Start_Learn = millis();//set to start millis state = CHECKING;//initial state } void Check_Alarm_And_Heartbeat() { unsigned long Mill = millis();//set to current time uint8_t alarmState = PINB&amp;8;//read alarm pin 3 uint8_t learnState = PINB&amp;16;//read learn pin 4 //main switch loop switch (state) { case CHECKING: //constant checking here if((alarmState) &amp;&amp; (!learnState)) { state = ALARMSEND;//set state Delay_Start_Check_Alarm = Mill;//keep time } //learn loop if((learnState) &amp;&amp; (!alarmState)) { state = LEARNSEND;//set state Delay_Start_Learn = Mill;//keep time } //continue heartbeat if((!alarmState) &amp;&amp; (!learnState)) { state = HEARTBEATTIMEOUT;//set state } //if both are high prioratize learnState/tamper signal if((alarmState) &amp;&amp; (learnState)) { state = LEARNSEND;//set state; learnState/tamper same signal Delay_Start_Learn = Mill;//keep time } break; case LEARNSEND: { state = LEARNTIMEOUT;//set state char LEARNFINAL[168];//make LEARNFINAL var and define length strcpy(LEARNFINAL, LEARN);//copy LEARN to new LEARNFINAL var for (uint8_t i = 0; i &lt; 7; i++) { strcat(LEARNFINAL, LEARN);// append/concatenate LEARN 7 times to LEARNFINAL } for (i = 0; i &lt; sizeof(LEARNFINAL); i++) { Send_Hex_Digit(DATA_PIN, LEARNFINAL[i], pulse);//send finished LEARNFINAL var } //PORTB &amp;= ~(1 &lt;&lt; DATA_PIN);//write low } break; case ALARMSEND: { state = ALARMTIMEOUT;//set state char ALARMFINAL[168];//make ALARMFINAL var and define length strcpy(ALARMFINAL, ALARM);//copy ALARM to new ALARMFINAL var for (uint8_t i = 0; i &lt; 7; i++) { strcat(ALARMFINAL, ALARM);// append/concatenate ALARM 7 times to ALARMFINAL } for (i = 0; i &lt; sizeof(ALARMFINAL); i++) { Send_Hex_Digit(DATA_PIN, ALARMFINAL[i], pulse);//send finished ALARMFINAL var } //PORTB &amp;= ~(1 &lt;&lt; DATA_PIN);//write low } break; case HEARTBEATSEND: { state = CHECKING;//change state char HEARTBEATPREFINAL[160];//make HEARTBEATPREFINAL var and define length strcpy(HEARTBEATPREFINAL, HEARTBEAT);//copy HEARTBEAT to new HEARTBEATPREFINAL var for (uint8_t i = 0; i &lt; 7; i++) { strcat(HEARTBEATPREFINAL, HEARTBEAT);// append/concatenate HEARTBEAT 7 times to HEARTBEATPREFINAL } for (i = 0; i &lt; sizeof(HEARTBEATPREFINAL); i++) { Send_Hex_Digit(DATA_PIN, HEARTBEATPREFINAL[i], pulse);//send finished HEARTBEATPREFINAL var } } break; case HEARTBEATTIMEOUT: state = CHECKING;//change state if ((Mill - Delay_Start_Heartbeat) &gt;= DELAY_TIME_ZONE_HEARTBEAT) { Delay_Start_Heartbeat += DELAY_TIME_ZONE_HEARTBEAT;//prevents drift state = HEARTBEATSEND;//change state when time ends } break; case ALARMTIMEOUT: state = ALARMTIMEOUT;//change state if ((Mill - Delay_Start_Check_Alarm) &gt;= DELAY_TIME_CHECKALARM_TIMEOUT) { state = CHECKING;//change state when time ends } break; case LEARNTIMEOUT: state = LEARNTIMEOUT;//change state if ((Mill - Delay_Start_Learn) &gt;= DELAY_TIME_CHECKLEARN_TIMEOUT) { state = CHECKING;//change state when time ends } break; default: //do nothing break; } } void Send_Hex_Digit(uint8_t pin, char c, uint16_t pulse) { byte bc = c - 48 ; // convert c to number 0 to 15 for (int i = 3; i &gt;= 0; i--) { bitWrite(PORTB, pin, bitRead(bc, i)); delayMicroseconds(pulse); } } void loop() { Check_Alarm_And_Heartbeat(); } </code></pre>
<p>After implementing the suggestions I was able to make the sketch smaller and also solve the unwanted transmitting for the 2 timeouts (<code>pin3</code>, <code>pin4</code>).</p> <p>The main issue was a 7s timeout before the sketch checks the High/Low.</p> <p>This was solved by setting <code>Delay_Start_Check_Alarm</code> and <code>Delay_Start_Learn</code> in my switch statement, if the alarm was triggered.</p> <pre><code> Delay_Start_Check_Alarm = Mill;//Setting this solved the issue </code></pre> <p>The heartbeat did not need this change since it gets set every time <code>HEARTBEATTIMEOUT</code> is called so it works ok.</p> <p>The code in the question is also updated.</p> <p>Big thanks to <em>@chrisl</em>, <em>@6v6gt</em> and <em>@timemage</em>.</p>
94501
|arduino-mkr|mkr1010wifi|
Arduino MKR WiFi 1010 memory management
2023-10-01T21:58:14.917
<p>according to the official documentation of the Arduino, the SRAM memory (which is allocated for the local variables) should be automatically released after calling any function. For example, I have a function <code>memory_allocate_test2</code>, which declares a large char array and this function is called in the loop(). I expect, that every time, after the function <code>memory_allocate_test2</code> is executed, the SRAM memory that I allocated for the local variables within that function should be freed or released. However, it is not working like that. When I call that function in a loop() the microcontroller hangs and stops working because it runs out of the available SRAM memory. Let me provide an example code:</p> <pre><code>void setup() { //Initialize serial and wait for port to open: Serial.begin(9600); while (!Serial) { ; // wait for serial port to connect. Needed for native USB port only - development mode. It has to be removed when releasing to live!!! } } void loop() { delay(2000); memory_allocate_test2(); } void memory_allocate_test2() { Serial.println(&quot;memory_allocate_test2 STARTING &quot;); display_freeram(); Serial.println(&quot;------------------------------------------------------------&quot;); Serial.println(&quot;Allocating the memory for the MKR: &quot;); char* memory_usage_test = new char[2000]; Serial.println(&quot;Allocated memory!&quot;); display_freeram(); Serial.println(&quot;------------------------------------------------------------&quot;); } extern &quot;C&quot; char* sbrk(int incr); void display_freeram(){ Serial.print(F(&quot;- SRAM left: &quot;)); Serial.println(freeRam()); } int freeRam() { char top; return &amp;top - reinterpret_cast&lt;char*&gt;(sbrk(0)); } </code></pre> <p>why it doesn't work as it states in the documentation? what I'm doing wrong? why the SRAM memory is not released each time after the <code>memory_allocate_test2</code> function execution?</p> <p><a href="https://www.seeedstudio.com/blog/2021/04/26/managing-arduino-memory-flash-sram-eeprom/" rel="nofollow noreferrer">https://www.seeedstudio.com/blog/2021/04/26/managing-arduino-memory-flash-sram-eeprom/</a></p> <p>when I execute that program, here is what happens:</p> <p>memory_allocate_test2 STARTING</p> <ul> <li>SRAM left: 7163</li> </ul> <hr /> <p>Allocating the memory for the MKR: Allocated memory!</p> <ul> <li>SRAM left: 5155</li> </ul> <hr /> <p>memory_allocate_test2 STARTING</p> <ul> <li>SRAM left: 5155</li> </ul> <hr /> <p>Allocating the memory for the MKR: Allocated memory!</p> <ul> <li>SRAM left: 3147</li> </ul> <hr /> <p>memory_allocate_test2 STARTING</p> <ul> <li>SRAM left: 3147</li> </ul> <hr /> <p>Allocating the memory for the MKR: Allocated memory!</p> <ul> <li>SRAM left: 1139</li> </ul> <hr /> <p>memory_allocate_test2 STARTING</p> <ul> <li>SRAM left: 1139</li> </ul> <hr /> <p>Allocating the memory for the MKR: Allocated memory!</p> <ul> <li>SRAM left: -869</li> </ul> <hr /> <p>memory_allocate_test2 STARTING</p> <ul> <li>SRAM left: -869</li> </ul> <hr /> <p>Allocating the memory for the MKR:</p> <p>at that point the device just hangs and stops working. That's not what I expect!</p> <p>since the functionality differs for each board and microcontroller, here are my specs: the board name is &quot;<strong>Arduino® MKR WiFi 1010</strong>&quot;, the microcontroller name is &quot;<strong>SAMD21 Cortex®-M0+ 32bit low power ARM MCU</strong>&quot;</p>
<p>You are mixing two different ways of memory allocation.</p> <p>The automatic memory allocation and release you cite works with defined local variables. These variables are allocated on the stack. At the end of their scope, their memory is released. To mimic your example:</p> <pre class="lang-cpp prettyprint-override"><code>void memory_allocate_test3() { Serial.println(&quot;memory_allocate_test3 STARTING &quot;); display_freeram(); Serial.println(&quot;------------------------------------------------------------&quot;); Serial.println(&quot;Allocating the memory for the MKR: &quot;); char memory_usage_test[2000] = &quot;Some content...&quot;; Serial.println(&quot;Allocated memory!&quot;); display_freeram(); Serial.println(&quot;------------------------------------------------------------&quot;); } </code></pre> <p>But what you use is heap-allocated memory because of the <code>new</code> operator. This kind of allocation is under complete responsibility of the programmer, this is you. Since you only allocate and never release, each loop reduces the remaining RAM. Use <code>delete</code> (actually <code>delete[]</code>) to release:</p> <pre class="lang-cpp prettyprint-override"><code>void memory_allocate_test2() { Serial.println(&quot;memory_allocate_test2 STARTING &quot;); display_freeram(); Serial.println(&quot;------------------------------------------------------------&quot;); Serial.println(&quot;Allocating the memory for the MKR: &quot;); char* memory_usage_test = new char[2000]; Serial.println(&quot;Allocated memory!&quot;); display_freeram(); Serial.println(&quot;------------------------------------------------------------&quot;); delete[] memory_usage_test; } </code></pre> <hr /> <p><strong>Beware:</strong> There are different allocation methods, <code>malloc</code>/<code>calloc</code>/<code>alloca</code>/<code>free</code> and <code>new</code>/<code>delete</code>. The former method uses functions of the C standard library, the latter method uses keywords of C++.</p> <p>The pointers returned by the different methods are not compatible. You cannot release memory by <code>free</code> that you allocated by <code>new</code>. The same holds true for <code>delete</code>/<code>malloc</code>.</p> <p>However, you can use both methods in the same program.</p> <p>Please learn about memory allocation before attempting to use it. C and C++ are error-prone to the unsuspecting user.</p> <p>As a side note, C and C++ are different languages, even though you can build a mixed program.</p>
94527
|arduino-uno|serial|nrf24l01+|
RF24 if statements are not reading properly, even if an "if" value is wrong, it still follows the associated code
2023-10-06T23:56:28.417
<p>My code is taking values from a remote and transmitting the state of it. Right now the states are just 1 and 0, on or off, and is writing over the serial monitor on the transmitting Arduino. On the receiving RF module I can't seem to get my if statements working right</p> <p>Transmitter code:</p> <pre><code>const char a[] = &quot;1&quot;; const char b[] = &quot;0&quot;; void loop() { if (Serial.available ( ) &gt; 0) { char state = Serial.read(); // reading the value from the remote if (state &gt;= 0) { digitalWrite (7, HIGH); //turning LED on transmitting breadboard on to compare to recieving breadboard radio.write(&amp;a, sizeof(a)); //tell the other arduino that the value is 1 } if (state &lt; 0) { digitalWrite(7,LOW); radio.write(&amp;b,sizeof(b)); //tell other arduino value is 0 } } </code></pre> <p>reciever code:</p> <pre><code>void loop() { if (radio.available()) { char state[32] = {0}; radio.read(&amp;state, sizeof(state)); Serial.println(state); int a = state; if (a = 1); { digitalWrite(7,HIGH); Serial.println(&quot;do something&quot;); } if (a = 0); { digitalWrite(7,LOW); Serial.println(&quot;do nothing&quot;); } } </code></pre> <p>receiving serial monitor</p> <pre><code>1 do something do nothing 0 do something do nothing 0 do something do nothing </code></pre> <p>and my light stays off on the receiving Arduino, why does it print both statements? A is 1, but it prints the value that's supposed to be printed when a is 0 also, i'm so confused</p>
<pre><code>if (a = 1); { digitalWrite(7,HIGH); Serial.println(&quot;do something&quot;); } </code></pre> <p>Two major problems here. In C++ you test for equality for <code>==</code>, not <code>=</code>.</p> <p>Second, putting the semicolon after the <code>if</code> terminates the scope of the <code>if</code>.</p> <p>That should read:</p> <pre><code>if (a == 1) { digitalWrite(7,HIGH); Serial.println(&quot;do something&quot;); } </code></pre> <hr /> <pre><code>char state[32] = {0}; radio.read(&amp;state, sizeof(state)); Serial.println(state); int a = state; </code></pre> <p><code>state</code> is an array. If you assign that to <code>a</code> you will get the same array, in another variable. That array will not be zero or one.</p> <p>Maybe you mean:</p> <pre><code>int a = state [0]; </code></pre>
94534
|audio|frequency|oscillator-clock|
Frequency problems with DIY arduino and resonator
2023-10-07T12:47:01.143
<p>I made a simple music program using an arduino Uno and the <code>tone()</code> function. It works fine.</p> <p>I decided to build my own circuit using a barebones AVR and upload that program. I did not know exactly what frequency was being used by the arduino, so I used a Murata resonator, with a frequency of 8 MHz.</p> <p>When I put my circuit to the test, the music that I had generated was played an octave lower, and its duration was doubled (taking twice the time to finish played a note).</p> <p>I figured out that I used the wrong resonator frequency. Indeed, I found out that the Arduino Uno used a 16 MHz resonator. Since I had half that frequency in my clock, the tone would be lower frequency, and it would take twice the time to finish a note. This made sense.</p> <p>So I went ahead and rebuilt the circuit with a 16 MHz resonator frequency. However, now I have the opposite effect!</p> <p>All the notes are one octave higher compared to my original Arduino Uno design, and the note duration finished in hald the time compared to the original Arduino Uno design... This suggests that I now have doubled the frequency compared to the original design (and four times the frequency compared to my first custum circuit attempt).</p> <p>I cannot seem to understand why this is happening, because right now I have the frequency that the original Arduino uses....</p>
<p>If the code runs at twice at the expected speed when clocked at 16 MHz, this can only be because either:</p> <ul> <li>you fixed the program to run correctly when clocked at 8 MHz</li> <li>you told the IDE that you are using a 8 MHz clock.</li> </ul> <p>The IDE comes with a few configurations that are suitable for an 8 MHz clock. If you select as a board “Arduino Pro or Pro Mini”, you have something equivalent to an Arduino Uno, except that you can choose between an 8 MHz clock and a 16 MHz clock (and also between an ATmega168 and a 328P).</p>
94542
|programming|motor|timers|
Problem with Bing generated code for automated chicken coop door
2023-10-08T12:42:03.920
<p>Glenn from Sweden here. I was wondering if some kind soul could help me out here.</p> <p>My partner bought a cheap chinese knock-off automatic chicken coop door that operates based on sunlight. <a href="https://www.amazon.se/dp/B0C18STKD6?psc=1&amp;ref=ppx_yo2ov_dt_b_product_details" rel="nofollow noreferrer">Link to the actual chicken coop door</a> In the morning the door opens and at the evening the door closes. It does this (from my humble understanding) with a LDR, a 5v dc motor and a small circuit board. The main problem is that the door opens way to early (about 07:00 am) with the risk that predators may snatch the chickens and there is no way to regulate the opening/closing times.</p> <p>What I would like is the following: I would like the door to open at 10:00am and close at 21:00pm every day of the week using the existing 5v motor. I do have some 28BYJ-48 step motors and A3967 driver boards I bought 10+ years ago, but then I would have to start modify physical things to get it to fit. I rather not do that if it’s possible to use the original parts.</p> <p>Now, coding is way over my head. Some people can draw beautiful things with paints and brushes, others can not. I can get some LED's to flash but I just can’t wrap my head around ”advanced” coding like this project. That is why I, out of desperation, tried to get Bing A.I. to write the code for me. <strong>I can compile the code without any errors, but it doesn’t work IRL. The motor does not start at the specified time, and sometimes the motor starts to spin out of the blue but doesn’t stop spinning.</strong> I have installed ”Time (1.6.1) by Michael Margolis” in the Arduino Library Manager to get the timer function to work. Is that the problem?</p> <p>I must mention here that the three leads from the SN754410 originally was routed to pins 7,8,9 on the Arduino, but since it didn't work I tried switching them to 3,5,6 in case it had something to do with the analog output?</p> <p>With the original electronics the door opens and closes mechanical fine, but I don’t understand how the ”brain” knows when to stop the motor so it doesn’t start to crunch the gear on the motor. There are no microswitches at the end points or anything…</p> <p>I added the red and green LED's (got Bing to include them in the code) just to be able to see when the door opens/closes if dark outside).</p> <p>I understand a Fritzing layout is preferable so I did my best to create one. Its my first time so please bear that in mind.</p> <p><a href="https://i.stack.imgur.com/05Acn.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/05Acn.jpg" alt="ritzing circuit layout" /></a></p> <p><a href="https://i.stack.imgur.com/mJeM9.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/mJeM9.jpg" alt="Chicken coop door" /></a></p> <pre><code> // Include the Time library #include &lt;TimeLib.h&gt; // Define the pins for the motor controller #define ENA 6 #define IN1 5 #define IN2 3 // Define the pins for the LEDs #define GREEN_LED 10 #define RED_LED 11 // Define the times for the motor actions #define START_TIME 1825 // 10:25 AM in 24-hour format #define END_TIME 1925 // 21:25 PM in 24-hour format #define DURATION 20 // 20 seconds // Define a variable to store the current time int currentTime; // Define a variable to store the motor state int motorState; // Define the motor states #define STOPPED 0 #define CLOCKWISE 1 #define COUNTERCLOCKWISE 2 void setup() { setSyncProvider(getTime); // Set the motor pins as outputs pinMode(ENA, OUTPUT); pinMode(IN1, OUTPUT); pinMode(IN2, OUTPUT); // Set the LED pins as outputs pinMode(GREEN_LED, OUTPUT); pinMode(RED_LED, OUTPUT); // Stop the motor and turn off the LEDs initially stopMotor(); turnOffLEDs(); // Set the time to sync with the computer's time setTime(17,27,10,7,10,2023); // hour,minute,second,day,month,year } void loop() { // Get the current time in HHMM format currentTime = hour() * 100 + minute(); // Check if the current time matches the start time or the end time if (currentTime == START_TIME || currentTime == END_TIME) { // Check the motor state and switch it accordingly switch (motorState) { case STOPPED: // Start the motor clockwise and turn on the green LED startMotor(CLOCKWISE); turnOnLED(GREEN_LED); break; case CLOCKWISE: // Stop the motor and start it counterclockwise after DURATION seconds and switch the LEDs accordingly stopMotor(); turnOffLED(GREEN_LED); delay(DURATION * 1000); startMotor(COUNTERCLOCKWISE); turnOnLED(RED_LED); break; case COUNTERCLOCKWISE: // Stop the motor and start it clockwise after DURATION seconds and switch the LEDs accordingly stopMotor(); turnOffLED(RED_LED); delay(DURATION * 1000); startMotor(CLOCKWISE); turnOnLED(GREEN_LED); break; } } } // A function to stop the motor void stopMotor() { // Set the enable pin to low digitalWrite(ENA, LOW); // Set the motor state to stopped motorState = STOPPED; } // A function to start the motor in a given direction void startMotor(int direction) { // Set the enable pin to high digitalWrite(ENA, HIGH); // Set the input pins according to the direction if (direction == CLOCKWISE) { digitalWrite(IN1, HIGH); digitalWrite(IN2, LOW); motorState = CLOCKWISE; } else if (direction == COUNTERCLOCKWISE) { digitalWrite(IN1, LOW); digitalWrite(IN2, HIGH); motorState = COUNTERCLOCKWISE; } } // A function to turn on a given LED pin void turnOnLED(int ledPin) { // Set the LED pin to high digitalWrite(ledPin, HIGH); } // A function to turn off a given LED pin void turnOffLED(int ledPin) { // Set the LED pin to low digitalWrite(ledPin, LOW); } // A function to turn off both LEDs void turnOffLEDs() { // Turn off both LED pins turnOffLED(GREEN_LED); turnOffLED(RED_LED); } // A function that gets the time from the computer time_t getTime() { // Check if there is serial data available if (Serial.available()) { // Read the serial data and convert it to a time_t value time_t t = Serial.parseInt(); // Return the time value if it is valid if (t &gt;= 946684800) { // Check if the value is after 1 Jan 2000 return t; } } // Return a zero value if there is no valid time return 0; } </code></pre>
<p>Using generative AI is only really helpful, if you have enough knowledge to work further with the generated code. Current LLMs are not as plug and play as many believe them to be.</p> <p>Timemages idea of covering the LDR with an LED in your control seems very reasonable. Then you don't need to hassle with the motors. Try taping one if your LEDs to the sensor and use a blink code to test that. You might need a brighter LED, depending on the LDR. Just make sure to use a transistor in low side switch configuration, if the needed current for the LED is greater than 20mA, which is the maximum continous current for a digital output pin (small bipolar transistors are very cheap; you will find much information online when searching for something like arduino transistor low side switch).</p> <p>Then about the time keeping: The Arduino itself is not good at keeping time accurately over a longer span. Due to manufacturing differences and temperature clock drift your time will be very much off after some days. For this you need a RTC (Real Time Clock). It has a very precise internal clock, so it can keep time accurately over long timestamps. You can buy ready to use RTC modules which also include a battery backup, so that the clock doesn't loose time on powerloss. Often these modules are build with the DS3231. There are also libraries for this RTC, for example <a href="https://github.com/jarzebski/Arduino-DS3231/tree/dev" rel="nofollow noreferrer">this one</a>. Look at the provided alarm example, because that is what you want (code triggering on specific times of the day). Use that example as starting point and make the LED turn on and off at these alarms. That are only small changes to the existing example code.</p>
94553
|interrupt|stm32|
Rising and falling edge on GPIO_STM32G4
2023-10-10T11:27:56.717
<p>I am working with STM32G491RE.I am giving pulse to GPIO pin from function generator. That pulse will be 2 msec on time and 8msec off time.I need to make flag high if the signal from function generator lost. Can anyone suggest me how to do this?</p> <pre><code>void HAL_GPIO_EXTI_Callback(uint16_t GPIO_Pin) { if(GPIO_Pin==detect_Pin){ if(HAL_GPIO_ReadPin(detect_GPIO_Port,detect_Pin)==GPIO_PIN_SET){ HAL_UART_Transmit(&amp;huart2, (uint8_t *)&quot;rising:&quot;,7, HAL_MAX_DELAY); } else if(HAL_GPIO_ReadPin(detect_GPIO_Port,detect_Pin)==GPIO_PIN_RESET){ HAL_UART_Transmit(&amp;huart2, (uint8_t *)&quot;falling:&quot;,8, HAL_MAX_DELAY); } else { HAL_GPIO_WritePin(led_GPIO_Port,led_Pin,GPIO_PIN_SET); } </code></pre> <p>I tried with EXTI interrupt but If input is there from generator its detecting both rising and falling edge and if there is no signal from generator I am not getting in to else condition.</p> <p><a href="https://i.stack.imgur.com/dIOOK.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/dIOOK.png" alt="img: pulse input from function generator." /></a></p> <p>1.If I want to make flag high for no signal from function generator,above image offtime also it considering as no signal.</p> <p>can anyone suggest how to do?</p> <p>Thanks</p>
<p>I do not know how to use the HAL API you are using. I will instead suggest an approach based on the Arduino API, which is more suitable for this site.</p> <p>Take note of the current time on every transition you detect. When the time since the last detected transition is longer than a predefined timeout, you know the pulse train has stopped:</p> <pre class="lang-cpp prettyprint-override"><code>const uint8_t pulse_pin = 2; const uint32_t pulse_timeout = 10; // milliseconds volatile uint32_t last_input_change; // last time we detected a change void on_input_change() { last_input_change = millis(); } void setup() { Serial.begin(9600); attachInterrupt(digitalPinToInterrupt(pulse_pin), on_input_change, CHANGE); } void loop() { // Avoid a data race while reading last_input_change. noInterrupts(); uint32_t last_input_change_copy = last_input_change; interrupts(); if (millis() - last_input_change_copy &gt;= pulse_timeout) Serial.println(&quot;The pulse train stopped.&quot;); } </code></pre> <p>Note that, for this to work, your whole code should be non-blocking, which is a good practice in any case.</p>
94556
|power|servo|softwareserial|arduino-pro-mini|reset|
How can I get servos to not brownout my Arduinos and power supply?
2023-10-11T00:22:45.687
<p>I have a problem with a project where one servo is resetting (browning out) two Arduino Pro Minis running 3.3v/8mHz. The two Arduinos are connected by SoftwareSerial on pins 9 and 10 and the slave sends yaw data to the master Arduino obtained from an MPU9250 breakout board. The power supply can supply 1 A of current. The servo is a small 2g servo that takes 3.3v at 50mA when moving (measured, not from the datasheet). Everything is hooked up on a breadboard. In case you're wondering, I am using an adaptation of the ServoTimer2 library to control the servos so as to not interfere with SoftwareSerial. I am baffled as to why one small servo is resetting two Arduinos. The Arduinos, along with the MPU9250, are only drawing 10mA. Could back EMF be causing the brownout?</p> <p>In the past, I have done a similar circuit but with only one Arduino obtaining sensor data and not sending it over SoftwareSerial. This works completely fine with two servos, a Pro Mini, and an MPU9250 breakout board. This leads me to think it is some sort of software issue.</p> <p>I have already received some guidance on the Arduino Discord stating to connect ceramic capacitors close to the servos, and this seems to sort of work, but I'm wondering if there might be a software way to do it with the least number of components possible.</p> <p>Any help would be greatly appreciated!</p>
<p><em>Note: Commonly you cannot use software to circumvent physics.</em></p> <p>Your symptoms show that the initial current of the servo is too high for your power concept to maintain the voltage. Therefore your Nanos brown out.</p> <p>An electric motor can easily take a multiple of its average current on acceleration. If blocked, and in the first moment it <em>is</em> blocked by the inertia, you can observe factors in low tens. From 50 mA to 1 A it's just a factor of 20...</p> <p>Please note that servos often control their motors with PWM, and you measure only the average. During the &quot;active&quot; state the current is higher, and depending on the motor's inductive properties can have &quot;strange&quot; wave forms.</p> <p>Additionally, each wire adds an inductive and resistive component in series with your Nanos and the servo. The shorter and thicker the wires, the better.</p> <p>So your case looks quite simple, and you have options:</p> <ul> <li>Decouple your power supply with appropriate capacitors. Ceramics with some tens of nF and an electrolyte or tantalum capacitor with some µF are common to provide the necessary current &quot;reservoir&quot; for the initial moment in different frequency ranges. Put them near the servo(s).</li> <li>Use a separate power supply for the servo(s). Do not forget to connect the grounds. But also here you might need capacitor(s) to avoid browning out the servo.</li> </ul>
94567
|timers|arduino-micro|wave|
Square wave generator generates a shorter pulse from time to time
2023-10-12T12:49:42.330
<p>I am using an arduino Micro to generate 8 square waves on 8 pins. The idea is as follows: on pin 13 is the main square wave. It represents a certain BPM (beats per minute). The other 7 pins should give multiplications or divisions of that BPM.</p> <p>It uses timer1 to trigger an interrupt at BPM/192 (this number is choosen to enable easy multiplications). It counts those interrupts and changes the states of the outputs when needed.</p> <p>The codes seems to run fine for most divisions and most multiplications. However in certain cases like /2, there seem to be shorter pulses from time to time that throw the whole timing off.</p> <p>Adding a short delay at the end of the loop seems to make the system more stable but still the short pulses appear from time to time.</p> <p>Does anyone have an idea what the problem might be.</p> <p><a href="https://i.stack.imgur.com/TYjig.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/TYjig.jpg" alt="Oscilloscope reading" /></a></p> <pre><code>int counter[8] = {0,0,0,0,0,0,0,0}; //storing number of interrupts since last pulse int trip[8] = {191,383,767,1535,3071,6143,12287,24575}; //number of interrupts needed for div/mult int outputPin[8] = {13,12,11,10,9,8,7,6}; void setup() { for (int x = 0; x &lt; 8; x++){ pinMode(outputPin[x], OUTPUT); digitalWrite(outputPin[x], HIGH); } cli(); TCCR1A = 0; TCCR1B = 0; TCNT1 = 0; OCR1A =2602; // 16000000 / (x * 8) -1 TCCR1B |= (1 &lt;&lt; WGM12); TCCR1B |= (0 &lt;&lt; CS12) | (1 &lt;&lt; CS11) | (0 &lt;&lt; CS10);//prescaler of 8 TIMSK1 |= (1 &lt;&lt; OCIE1A); sei(); } void pulse(){ for (int count = 0; count &lt; 8; count++){ counter[count]++; } } ISR(TIMER1_COMPA_vect){ pulse(); } void loop() { for (int y = 0; y &lt; 8; y++){ if(counter[y] &gt; trip[y]){ digitalWrite(outputPin[y],!digitalRead(outputPin[y])); counter[y] = 0; } } delayMicroseconds(100); } </code></pre>
<p>There are two issues here:</p> <ol> <li><p>There is a data race on <code>counter[]</code>: it can be modified in interrupt context while it is being read (or even modified) by the main program.</p> </li> <li><p>Clearing <code>counter[y]</code> will make you loose ticks if for some reason (say some interrupt) you do it a little bit late. You should instead decrement it by <code>trip[channel]</code>.</p> </li> </ol> <p>Here is a safe way of managing the counters:</p> <pre class="lang-cpp prettyprint-override"><code>volatile int counter[8] = {...}; // don't forget `volatile` // Return whether this channel has tripped, and update the count. bool tripped(int channel) { noInterrupts(); bool did_trip = counter[channel] &gt;= trip[channel]; if (did_trip) counter[channel] -= trip[channel]; interrupts(); return did_trip; } void loop() { for (int y = 0; y &lt; 8; y++) if (tripped(y)) digitalWrite(outputPin[y], !digitalRead(outputPin[y])); } </code></pre> <p>Notice that the critical section (the section with interrupts disabled) lives within the <code>for</code> loop, rather than around it. It is better to have multiple small critical sections rather than one large one.</p> <p><strong>Edit 1</strong>: You don't need the delay. It makes the system “more stable” because it reduces the likelihood that, on any given TIMER1_COMPA interrupt, the main program is accessing the counters (as it will spend most of its time delaying). Adding this delay is in a way treating the symptoms rather than the root cause of the data race.</p> <p><strong>Edit 2</strong>: Answering a comment. If you want the squares waves to stay in sync, their frequency ratios should be integers. In your program, this is almost, but not quite the case. For example, if you look at the ratio between the first two channels:</p> <p>channel 0: 191 interrupts per signal toggle<br /> channel 1: 383 interrupts per signal toggle<br /> ratio: 383 ÷ 191 ≈ 2.0052</p> <p>The easy fix is to add 1 to every element of the <code>trip</code> array (384 ÷ 192 is <em>exactly</em> 2).</p>
94607
|array|debugging|progmem|sketch-size|
Large arrays crash the arduino
2023-10-18T14:48:59.140
<p>I have three large <code>PROGMEM</code> arrays, in order to store musical notes for a song. One array is the notes, one is the note durations, and one is the pause after the note.</p> <p>The first array is an <code>int</code> one and the other two are <code>floats.</code> The program works, but after a specific number of elements, the arduino crashes. Meaning, I upload the program without problems, but the device does nothing.</p> <p>When I have 227 elements (in all three arrays) obviously, the program works. If I increase the number of elements to 228, nothing happens when I upload...</p> <p>When the IDE says <code>avrdude: 10606 bytes of flash verified</code> then everything works. When the size gets increased to <code>10616</code>, everything crashes. Is this normal behaviour?</p> <p><strong>EDIT:</strong> The code is trivial, the only important part of the code is this:</p> <pre><code>int number_of_stored_values_in_MelodyArray = sizeof(Crash_Melody) / sizeof(int); int Melody_Array[number_of_stored_values_in_MelodyArray]; memcpy_P(Melody_Array, Crash_Melody, sizeof Melody_Array); </code></pre> <p>I am using <code>memcpy_P()</code> in order to copy the arrays from <code>PROGMEM</code> to RAM. I do this for the int and the two float arrays. With 221 elements in each array, I guess I am out of RAM.</p> <p>The reason I have an array for the pause as well, is because I am using an online midi to tone() converter and that is the format that it uses. So I have to stick to that format.</p> <p>I think if I did the assignment incrementally - like for example copy only 20 elements from the array, play the song, then repeat until the end, I would have no problem.</p> <p>Is there a way for <code>memcpy_P()</code> to specify not the whole array to copy, but index them? Does it take a starting index value?</p> <p><strong>EDIT 2:</strong> This is a snippet of code after trying Edgar Bonnet's approach.</p> <pre><code>int number_of_stored_values_in_MelodyArray = sizeof(My_Melody) / sizeof(int); for (int i = 0; i &lt; number_of_stored_values_in_MelodyArray; i++) { int note = pgm_read_word(&amp;My_Melody[i]); float duration = pgm_read_word(&amp;My_noteDurations[i]); float pause_duration = pgm_read_word(&amp;My_Delay[i]); playMelodyExtended2(note, duration, pause_duration, number_of_stored_values_in_MelodyArray, 10, 400); } int playMelodyExtended2(int melody, float noteDuration, float pauseDuration, int number_of_notes, int music_pin, int delay_var) { for (int thisNote = 0; thisNote &lt; number_of_notes; thisNote++) { tone( music_pin, melody, noteDuration ); delay( pauseDuration ); noTone(music_pin); } delay(delay_var); } </code></pre> <p><strong>EDIT 3:</strong> This is the newest iteration of the code:</p> <pre><code> int number_of_stored_values_in_MelodyArray = sizeof(My_Melody) / sizeof(int); for (int i = 0; i &lt; number_of_stored_values_in_MelodyArray; i++) { int note = pgm_read_byte_near(&amp;My_Melody[i]); note &lt;&lt; 8; note += pgm_read_byte_near(&amp;My_Melody[i+1]); float duration = pgm_read_float_near(&amp;My_noteDurations[i]); uint16_t pause_duration = pgm_read_byte_near(&amp;My_Delay[i]); pause_duration &lt;&lt; 8; pause_duration += pgm_read_byte_near(&amp;My_Delay[i+1]); playMelodyExtended2(note, duration, pause_duration, number_of_stored_values_in_MelodyArray, 10, 400); } int playMelodyExtended2(int melody, float noteDuration, uint16_t pauseDuration, int number_of_notes, int music_pin, int delay_var) { for (int thisNote = 0; thisNote &lt; number_of_notes; thisNote++) { tone( music_pin, melody, noteDuration ); delay( pauseDuration ); // stop the tone playing: noTone(music_pin); } delay(delay_var); } </code></pre>
<p>In the edited version of your question, you wrote:</p> <blockquote> <p>I am using <code>memcpy_P()</code> in order to copy the arrays from <code>PROGMEM</code> to RAM.</p> </blockquote> <p>The whole purpose of <code>PROGMEM</code> is to <strong>avoid having to store the data in RAM</strong>. If you copy the arrays to RAM, you are defeating <code>PROGMEM</code>. Your Arduino has much more Flash than RAM, and it will crash if you eat up all the RAM. This is why the <code>PROGMEM</code> optimization is valuable whenever you have large arrays of constant data.</p> <p>The proper way to use those arrays is to copy to RAM one element at a time: get the data for the next note you have to play, then play it, then move to the next one. E.g.:</p> <pre class="lang-cpp prettyprint-override"><code>for (int i = 0; i &lt; melody_length; i++) { int note = pgm_read_word(&amp;Crash_Melody[i]); // etc... } </code></pre> <p>Copying small chunks to RAM, as you suggest in your question, would make the code more complex and add absolutely no value.</p> <hr /> <p><strong>Edit</strong>: In the second edit of your question, you have this:</p> <pre class="lang-cpp prettyprint-override"><code>float duration = pgm_read_word(&amp;My_noteDurations[i]); </code></pre> <p>What this does is:</p> <ul> <li>read the first two bytes of <code>My_noteDurations[i]</code> (which is a four-byte quantity, thus you are truncating it)</li> <li>interpret that as an integer (which it is not)</li> <li>convert that to <code>float</code></li> </ul> <p>The result will have little to do with the original number. The correct way to read a float from <code>PROGMEM</code> is to use <code>pgm_read_float()</code>.</p> <p>That being said, I see now that you use this number as a parameter for <code>delay()</code>. Given that this function takes an integer, there is no point in storing the delay as a float. This will only add a (somewhat costly) float-to-integer conversion to your program, with no added benefit. Also, since the delays are likely to be less than 65 seconds, a 16-bit unsigned integer should be enough.</p> <p>Further down, you have this:</p> <pre class="lang-cpp prettyprint-override"><code>for (int thisNote = 0; thisNote &lt; number_of_notes; thisNote++) { tone(music_pin, melody, noteDuration); delay(pauseDuration); noTone(music_pin); } </code></pre> <p>I fail to see the purpose of this loop. You are repeating <strong>each note</strong> a number of times that is equal to the total number of notes in the song. Why?</p> <hr /> <p><strong>Answer to edit 3</strong>: there are a few issues I can see in this version of the code.</p> <ol> <li><p>Consistency of the data types: in the previous version, it looked like the pause durations were floats. Now they are integers. You have to make sure you use the <code>pgm_read_*()</code> function suitable for the actual data type of the array.</p> </li> <li><p>Reading by bytes: there is no point in reading a 16-bit integer one byte at a time: use <code>pgm_read_word()</code> to read it all at once. Reading byte by byte only makes the code more complex and increases the chances of bugs. In fact, your way of reconstructing the numbers is buggy.</p> </li> <li><p>The loop in <code>playMelodyExtended2()</code> makes no sense to me. Please, try removing it.</p> </li> </ol> <p>Here is what I suggest at this point:</p> <pre class="lang-cpp prettyprint-override"><code>for (int i = 0; i &lt; number_of_stored_values_in_MelodyArray; i++) { int note = pgm_read_word(&amp;My_Melody[i]); float duration = pgm_read_float(&amp;My_noteDurations[i]); uint16_t pause_duration = pgm_read_word(&amp;My_Delay[i]); tone(10, note, duration); delay(pause_duration); } </code></pre> <p>This snippet makes some assumptions about the rest of your code, and specifically about the way your arrays are defined. If these assumptions are incorrect, this will not work. Thus, I second @orithena's comment and urge you to post a full, testable version of you sketch (three notes would be enough).</p>
94610
|interrupt|core-libraries|
Where to find interrupt flag for 3rd-party Arduino board cores?
2023-10-18T20:00:12.707
<p>This question might be a bit broad, but I'm running into an apparently classic problem with Arduino interrupts, where the rising or falling edge flag is triggered prior to a rising or falling edge technically occurring before a pin is pulled high/low and the microcontroller &quot;remembering&quot; that event occurred, running the interrupt the moment it gets attached to a pin. In this case, I'm working with Sparkfun's <a href="https://www.sparkfun.com/products/15484" rel="nofollow noreferrer">Artemis module</a> (using the <a href="https://cdn.sparkfun.com/assets/c/8/3/d/2/Apollo3-Blue-SoC-Datasheet.pdf?_gl=1*1ovb3x*_ga*MjExNjgxNTkwNy4xNjU5NjIyNDc0*_ga_T369JS7J9N*MTY5NzcyMTQ2Mi4zMS4wLjE2OTc3MjE0NjIuNjAuMC4w" rel="nofollow noreferrer">Apollo3 microcontroller</a>). The code in question can be seen below:</p> <pre><code>#define SLEEP_INTERRUPT 4 void setup { pinMode(SLEEP_INTERRUPT, INPUT); #ifdef DEBUG Serial.print(&quot;About to attach interrupt&quot;); #endif attachInterrupt(digitalPinToInterrupt(SLEEP_INTERRUPT), sleepModeSwitch, FALLING); #ifdef DEBUG Serial.print(&quot;Interrupt attached&quot;); #endif } void sleepModeSwitch() { #ifdef DEBUG Serial.print(&quot;Interrupt triggered! button status: &quot;); Serial.println(digitalRead(SLEEP_INTERRUPT)); #endif if(sleep_mode_status == false) { goToSleep(); } else { wakeUp(); } } void goToSleep() { sleep_mode_status = true; #ifdef DEBUG Serial.println(&quot;Going to sleep&quot;); delay(50); //Wait for serial to finish Serial.end(); //Power down UART(s) #endif // turn off the led. digitalWrite(LED_BUILTIN, LOW); // Stop the BLE advertising. BLE.stopAdvertise() ; powerControlADC(false); for(int x = 0; x &lt; 50; x++) { if(x != 4) { am_hal_gpio_pinconfig(x, g_AM_HAL_GPIO_DISABLE); } } //Power down Flash, SRAM, cache am_hal_pwrctrl_memory_deepsleep_powerdown(AM_HAL_PWRCTRL_MEM_CACHE); //Turn off CACHE am_hal_pwrctrl_memory_deepsleep_powerdown(AM_HAL_PWRCTRL_MEM_FLASH_512K); //Turn off everything but lower 512k am_hal_pwrctrl_memory_deepsleep_powerdown(AM_HAL_PWRCTRL_MEM_SRAM_64K_DTCM); //Turn off everything but lower 64k //am_hal_pwrctrl_memory_deepsleep_powerdown(AM_HAL_PWRCTRL_MEM_ALL); //Turn off all memory (doesn't recover) // // Enable interrupts to the core. am_hal_interrupt_master_enable(); // //Enable the timer interrupt in the NVIC. // NVIC_EnableIRQ(STIMER_CMPR6_IRQn); //Go to Deep Sleep. am_hal_sysctrl_sleep(AM_HAL_SYSCTRL_SLEEP_DEEP); } void wakeUp() { am_hal_pwrctrl_memory_deepsleep_powerdown(AM_HAL_PWRCTRL_MEM_MAX); // Re-enable UART0 pins am_hal_gpio_pinconfig(48, g_AM_BSP_GPIO_COM_UART_TX); am_hal_gpio_pinconfig(49, g_AM_BSP_GPIO_COM_UART_RX); am_hal_pwrctrl_periph_enable(AM_HAL_PWRCTRL_PERIPH_UART0); initializeADC(); #ifdef DEBUG Serial.begin(115200); Serial.println(&quot;Waking up! Hello world!&quot;); #endif deepSleepTimer = millis() ; sleep_mode_status = false; } </code></pre> <p>Based on my research, the solution for this is to just clear the interrupt flag manually before attaching the interrupt to your desired pin. Unfortunately, so far the methods for doing so that I've found only work for AVR boards, and I'm not certain where to look to find more information about how to access an interrupt flag in a sketch for a 3rd-party Arduino core. Does anyone have a suggestion or two on where to start?</p>
<blockquote> <p>the rising or falling edge flag is triggered prior to a rising or falling edge technically occurring before a pin is pulled high/low and the microcontroller &quot;remembering&quot; that event occurred, running the interrupt the moment it gets attached to a pin</p> </blockquote> <p>There is no &quot;technically&quot; about it. This is what is supposed to happen. Once you configure the interrupt to happen (as you do in <code>setup</code>) then the processor will remember that the condition has happened, whether or not interrupts are enabled.</p> <p>If you want the interrupt only to be processed <em>after</em> a certain point, then yes, you should clear the &quot;interrupt has happened&quot; flag in the MCU, before enabling interrupts.</p> <p>Your question is pretty non-specific about exactly which processors you are talking about, but I would certainly clear any appropriate flags before attaching the interrupt.</p> <blockquote> <p>I'm not certain where to look to find more information about how to access an interrupt flag in a sketch for a 3rd-party Arduino core</p> </blockquote> <p>The datasheet of the device on this particular core?</p> <hr /> <p>Judging by the <a href="https://cdn.sparkfun.com/assets/c/8/3/d/2/Apollo3-Blue-SoC-Datasheet.pdf" rel="nofollow noreferrer">datasheet for the Apollo3 Blue SoC</a>:</p> <blockquote> <p>6.3.2.15 INTCLR Register</p> <p>IO Master Interrupts: Clear</p> <p>OFFSET: 0x00000228</p> <p>INSTANCE 0 ADDRESS: 0x5000C228</p> <p>Write a 1 to a bit in this register to clear the interrupt status associated with that bit.</p> </blockquote> <p>However I don't have one of those processors around to test it.</p>
94640
|nrf24l01+|
How to connect nRF24L01+ with Arduino Giga R1?
2023-10-23T20:13:30.227
<p>I have bought 2 Arduino Giga R1, 2 nRF24L01+ modules and 2 nRF24L01+ adapters. I am using the Arduino SPI in order to connect it with nRF24L01+. And I am using <a href="https://www.circuits-diy.com/nrf24l01-wireless-rf-transceiver-module-working-interface-with-arduino-uno/" rel="nofollow noreferrer">the following code</a> with this change in the code only:</p> <pre class="lang-c prettyprint-override"><code>RF24 radio(7, 10); // CE, CSN </code></pre> <p>This is the Arduino GIGA R1 <a href="https://docs.arduino.cc/tutorials/giga-r1-wifi/cheat-sheet" rel="nofollow noreferrer">SPI documentation</a>, and this is the <a href="https://www.addicore.com/products/nrf24l01-pa-lna-with-antenna-2-4ghz-wireless-transceiver" rel="nofollow noreferrer">nRF24L01+ modules</a>, and <a href="https://www.addicore.com/products/nrf24l01-breakout-adapter-with-on-board-3-3v-regulator" rel="nofollow noreferrer">the related adapter</a> (the links of the modules are from a random Google search, just to show you the images + the documentation of the modules).</p> <p>However I don't see something working. I added the following command both in the Receiver and Transmitter codes:</p> <pre class="lang-c prettyprint-override"><code>SPI.begin(); SPI1.begin(); </code></pre> <p>in order to activate both SPI of each Arduino, because I don't know which is which. The result: Nothing works on Arduino GIGA R1... The same code above works fine on Arduino MEGA 2560 R3, <em><strong>so all the modules and the code are fine</strong></em>. The problem is on Arduino GIGA R1...</p> <p>I supply the nRF24L01+ and the related adapters with 5V/1.5A power supply. I supply each Arduino GIGA R1 with 5V/1.5A power supply.</p> <p>I have also tried <a href="https://www.hackster.io/hibit/how-to-use-the-nrf24l01-module-with-arduino-5bfb22" rel="nofollow noreferrer">this code</a>, and I got this message:</p> <blockquote> <p>We have lost connection, preventing unwanted behavior</p> </blockquote> <p>Does anyone has any idea how to make the 2 Arduino GIGA R1 communicate via the nRF24L01+ link?</p>
<p>I just want to note that You Do Not Need An External Antenna module, because the Arduino Giga R1 has a micro UFL antenna connector, and an antenna is shipped with every arduino giga(sorry for you if they forgot to include it in your one), However It IS probably more for wifi porpuses than enclosed communication, still the nRF24L01+ is a great way to actually communicate between two mcu's, especially if an mcu doesnt come with a built in wifi or some sort of wireless communication</p>
94644
|arduino-uno|code-review|
Sounds are being played at the same time
2023-10-24T09:40:41.540
<p>I'm making a school project that allows plants to 'talk'. As in when the plant is in an un-ideal environment (low or high soil moisture, not ideal temperature or humidity and not enough light). I have currently made some demo code for my presentation as the real code has real thresholds and is hard to trigger instantly during the presentation. The problem im facing is that the sound is almost always cut off by another one, how can i stop this, also the recordings are all 7 seconds or less.</p> <pre><code>#include &lt;DHT.h&gt; #include &lt;SoftwareSerial.h&gt; #include &lt;DFRobotDFPlayerMini.h&gt; #include &lt;LiquidCrystal_I2C.h&gt; //-----------------DEMO---CODE------- #define DHTPIN 3 #define DHTTYPE DHT22 #define SOIL_MOISTURE_PIN A0 #define LIGHT_SENSOR_PIN 2 #define TEMP_THRESHOLD 25.0 #define HUMIDITY_THRESHOLD 60 #define LIGHT_THRESHOLD 1 // 1 for dark, adjust as needed #define LOWER_SM_THRESHOLD 20 // Adjust as needed #define UPPER_SM_THRESHOLD 50 // Adjust as needed #define LCD_ADDR 0x27 // I2C address of the LCD #define LCD_COLUMNS 16 #define LCD_ROWS 2 #define MESSAGE_INTERVAL 20000 // 20 seconds in milliseconds DHT dht(DHTPIN, DHTTYPE); SoftwareSerial mySoftwareSerial(10, 11); // RX, TX for DFPlayer DFRobotDFPlayerMini myDFPlayer; LiquidCrystal_I2C lcd(LCD_ADDR, LCD_COLUMNS, LCD_ROWS); unsigned long lastTempTrigger = 0; unsigned long lastHumidityTrigger = 0; unsigned long lastSoilMoistureTrigger = 0; unsigned long lastLightTrigger = 0; void setup() { dht.begin(); Serial.begin(9600); mySoftwareSerial.begin(9600); myDFPlayer.begin(mySoftwareSerial); myDFPlayer.volume(30); // Initialize the LCD lcd.init(); lcd.backlight(); lcd.clear(); lcd.setCursor(0, 0); lcd.print(&quot;Initializing...&quot;); delay(2000); lcd.clear(); lcd.setCursor(0, 0); lcd.print(&quot;Plantastic!&quot;); lcd.setCursor(0, 1); lcd.print(&quot;System Ready&quot;); delay(2000); lcd.clear(); } void loop() { float temperature = dht.readTemperature(); float humidity = dht.readHumidity(); int lightValue = digitalRead(LIGHT_SENSOR_PIN); int soilMoistureValue = analogRead(SOIL_MOISTURE_PIN); int soilMoisturePercentage = 100 - (map(soilMoistureValue, 0, 1023, 0, 100)); if (temperature &gt; TEMP_THRESHOLD &amp;&amp; millis() - lastTempTrigger &gt;= MESSAGE_INTERVAL) { myDFPlayer.play(3); // Play &quot;Too Hot&quot; message lastTempTrigger = millis(); } else if (temperature &lt; TEMP_THRESHOLD &amp;&amp; millis() - lastTempTrigger &gt;= MESSAGE_INTERVAL) { myDFPlayer.play(1); // Play &quot;Too Cold&quot; message lastTempTrigger = millis(); } if (round(humidity) &lt; HUMIDITY_THRESHOLD &amp;&amp; millis() - lastHumidityTrigger &gt;= MESSAGE_INTERVAL) { myDFPlayer.play(2); // Play &quot;Low Humidity&quot; message lastHumidityTrigger = millis(); } if (soilMoisturePercentage &lt; LOWER_SM_THRESHOLD &amp;&amp; millis() - lastSoilMoistureTrigger &gt;= MESSAGE_INTERVAL) { myDFPlayer.play(6); // Play &quot;Thirsty&quot; message lastSoilMoistureTrigger = millis(); } else if (soilMoisturePercentage &gt; UPPER_SM_THRESHOLD &amp;&amp; millis() - lastSoilMoistureTrigger &gt;= MESSAGE_INTERVAL) { myDFPlayer.play(5); // Play &quot;Enough Water&quot; message lastSoilMoistureTrigger = millis(); } if (lightValue == 1 &amp;&amp; millis() - lastLightTrigger &gt;= MESSAGE_INTERVAL) { myDFPlayer.play(4); // Play &quot;It's dark in here&quot; message lastLightTrigger = millis(); } // Update the LCD display lcd.clear(); lcd.setCursor(0, 0); lcd.print(&quot;T: &quot;); lcd.print(temperature, 2); lcd.print(&quot; H: &quot;); lcd.print(humidity, 2); lcd.setCursor(0, 1); lcd.print(&quot;SM: &quot;); lcd.print(soilMoisturePercentage); lcd.print(&quot;% L: &quot;); lcd.print(lightValue == LIGHT_THRESHOLD ? &quot;Dark&quot; : &quot;Light&quot;); delay(1000); } </code></pre>
<p>There are 2 approaches which address the problem of not playing a sound to completion.</p> <ol> <li>Place a delay loop after each call to myDFPlayer.play() designed to last as long as the played sound. This is likely the most straight forward solution. However, adding delays where no other code is able to run is considered bad programming form. It also creates problem when adding new features to the program.</li> <li>Create a <a href="https://en.wikipedia.org/wiki/Finite-state_machine" rel="nofollow noreferrer">finite state machine</a> where the loop() function has no delays. Instead use a variable to track the state the state machine is in and only change that variable when the conditions to go to the next state have been satisfied. For instance, do nothing until a threshold (dryness, light, ect) has been crossed. At which point switch to the state where you play back the associated sound &amp; clear that threshold flag. Do not exit that state until millis() has increased past the duration of the played sound. Finally, repeat these state transitions for any other thresholds that have been crossed. Complex behaviors dealing with how long before repeating a sound can then be added with additional states.</li> </ol>
94659
|esp8266|pwm|speaker|
D1 mini ESP8266 no sound on speaker
2023-10-26T15:48:11.273
<p>I am new to Arduino and microcontrollers, I want to make a tone with my D1 mini and a <a href="https://cdn-reichelt.de/documents/datenblatt/I900/BL50A.pdf" rel="nofollow noreferrer">LSM-50F</a> speaker. But I don't get any output. Any idea what I am doing wrong? Tested it with two D1 mini boards.</p> <p>This is how I wired everything: <a href="https://i.stack.imgur.com/bpTsJ.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/bpTsJ.jpg" alt="enter image description here" /></a></p> <p>Specifications:</p> <pre><code>Impedance 45 Ohm Power (Nominal) 0,2 W Power (Maximum) 0,5 W Resonance frequency 450 Hz </code></pre> <p>The D1 mini's GPIO pins have a maximum of 10 mA, so I am using a 330 Ohm resistor in series to the 45 Ohm speaker to avoid overloading.</p> <pre><code>I = U/R I = 3.3 V / 330 Ohm + 45 Ohm I = 3.3 V / 375 Ohm I = 8.8 mA </code></pre> <p>My code:</p> <pre><code>int Speaker = 5; void setup() { } void loop() { tone(Speaker, 450); delay(1000); noTone(Speaker); } </code></pre> <p>I also tried a piezo from an old computer in the same setup. Not sure if the piezo is active or passive, so I tried using:</p> <pre><code>digitalWrite(Speaker, HIGH); // Play a tone on an active piezo. </code></pre> <p>And</p> <pre><code>tone(Speaker, 450); // Play a tone on a passive piezo. </code></pre>
<p>You are plugged into D5 and have <code>int Speaker = 5;</code> However, D5 and 5 are actually <a href="https://github.com/esp8266/Arduino/blob/3.1.2/variants/d1_mini/pins_arduino.h#L42" rel="nofollow noreferrer">different things</a>.</p> <pre><code>static const uint8_t D5 = 14; </code></pre> <p>The plain number refers to the GPIO number of the esp8266 chip. The &quot;D5&quot; type numbers that are silk screened are mapped onto those. So you need <code>int Speaker = D5;</code> or alternately <code>int Speaker = 14; /*D5 is GPIO14*/</code> or you need to move the wire to the actual GPIO5 which <a href="https://github.com/esp8266/Arduino/blob/3.1.2/variants/d1_mini/pins_arduino.h#L38C11-L38C11" rel="nofollow noreferrer">is labeled</a> <code>D1</code>.</p> <p>You may find your speaker is very quiet, maybe inaudible. If you're going to try driving a speaker from a GPIO pin the piezo is a better choice. But really it would be better to have some kind of amplification. <a href="https://www.murata.com/en-us/support/faqs/sound/sounder/char/sch0001" rel="nofollow noreferrer">This</a> is the sort of thing I've used with piezos before. You can test that you're affecting the pin at all with a meter. You may get a weird reading, but you should at least be able to tell the difference between that and a pin you aren't trying to use.</p>
94662
|arduino-uno|arduino-mega|
How to handle class initialization when using brace-enclosed initializer lists
2023-10-27T00:55:09.890
<p>I'm working with a custom C++ library, CPSTL, for Arduino, which includes a <code>cpstd::vector</code> class that is designed to work with <code>cpstd::initializer_list</code>, <code>cpstd::initializer_list</code> is supposed to mimic <code>std::initializer_list</code>.</p> <p>However, I'm having trouble initializing a <code>cpstd::vector</code> using brace-enclosed initializer lists.</p> <p>I've looked up many sources online, and it seems there is not a lot of information in the topic, but came up to things such as <a href="https://jfpoilpret.github.io/fast-arduino-lib/initializer__list_8h_source.html" rel="nofollow noreferrer">FastArduino: initializer list</a>, and <a href="https://github.com/mike-matera/ArduinoSTL/blob/master/src/initializer_list" rel="nofollow noreferrer">Arduino STL: Initializer list</a>. Giving me hopes that it is actually possible. (I can't use those libraries, because they lack the build system generation tools on the library I am developing, they also lack on customizability, and also as a good learning experience)</p> <p>I've tried various approaches, but I keep getting the error:</p> <blockquote> <p>could not convert '{0, 1, 2, 3, 4}' from 'brace-enclosed initializer list' to 'cpstd::vector'.</p> </blockquote> <p>Here's an example of the code that's causing the issue:</p> <pre class="lang-cpp prettyprint-override"><code> cpstd::vector&lt;unsigned char&gt; myVector = {0, 1, 2, 3, 4}; </code></pre> <p>I have already implemented a custom <code>cpstd::initializer_list</code> and constructor that should handle this, but the issue persists. Is there something specific to the Arduino environment that could be causing this issue?</p> <p>Additional Information:</p> <ul> <li><p>I have verified that the <code>cpstd::initializer_list</code> is correctly defined and included in my code.</p> </li> <li><p>The <code>cpstd::vector</code> class is included and accessible.</p> </li> <li><p>I have reviewed my <code>cpstd::vector</code> class, and the constructor for <code>cpstd::initializer_list</code> is correctly implemented.</p> </li> <li><p>While reading the error log, I noticed that <code>std::initializer_list</code> constructor has two parameters, a pointer to the data, and also a variable telling the length of the braced enclosed list, however I noticed that the list ends up casting to a single parameter, hence having no possible constructor to call</p> </li> </ul> <p><em><strong>What could be causing this issue, and how can I resolve it to initialize <code>cpstd::vector</code> using brace-enclosed initializer lists in the Arduino environment? I think the main issue is with boards that have no STL support. (i.e. AVR based boards)</strong></em></p> <p>I've came to the conclusion that it will not be possible to create such constructors/operators due to compiler limitations, I think I've tried anything that came to mind. But I don't want to give up on this without knowing if there is a workaround.</p> <p><strong>edit (removed previous code snippets for clarity, added minimal code example reproducing the error) :</strong></p> <p>minimal sketch reproducing the error:</p> <pre><code>#include &lt;Arduino.h&gt; #include &lt;stddef.h&gt; namespace cpstd { template&lt;typename T&gt; class initializer_list { public: using value_type = T; using reference = const T&amp;; using const_reference = const T&amp;; using size_type = size_t; using const_iterator = const T*; private: const_iterator _M_array; size_type _M_len; constexpr initializer_list(const T* array, size_type size) noexcept : _M_array(array), _M_len(size) {} public: constexpr initializer_list() noexcept : _M_array(nullptr), _M_len(0) {} constexpr size_type size() const noexcept { return _M_len; } constexpr const_iterator begin() const noexcept { return _M_array; } constexpr const_iterator end() const noexcept { return _M_array + _M_len; } }; } template&lt;typename T&gt; class exampleClass{ protected: T buffer[10]; size_t len; public: exampleClass(): len(0) {} exampleClass(cpstd::initializer_list&lt;T&gt; il){ len = il.size(); for(size_t i = 0; i &lt; len; i++){ buffer[i] = *(il.begin()+i); } } exampleClass&amp; operator=(cpstd::initializer_list&lt;T&gt; il){ len = il.size(); for(auto i = il.begin(); i &lt; il.end(); i++){ buffer[i] = *i; } } size_t size() const {return len;} T data(size_t x) const {return buffer[x];} }; void setup() { // put your setup code here, to run once: Serial.begin(115200); exampleClass&lt;uint8_t&gt; myObject = {0,1,2,3}; Serial.println(myObject.size()); Serial.println(myObject.data(0)); Serial.println(myObject.data(1)); Serial.println(myObject.data(2)); Serial.println(myObject.data(3)); } void loop() { // put your main code here, to run repeatedly: } </code></pre>
<p>So I have been messing around with the minimal example code and found a working solution, I'll post the solution just in case someone finds themselves having the same issue on the future, the only downside is that it feels a bit hacky to my taste, I still wonder if there is a better solution. And would gratly appreciate any feedback.</p> <p>I found out that the compiler does not ackowledges the initializer_list class for braced enclosed initializers if the class is not under the namespace std.</p> <p>The way I came arround this problem lies on using the preprocessor directive below:</p> <pre><code>#if __has_include(&lt;initializer_list&gt;) </code></pre> <p>With this line conditional compilation takes place, and we can specify what to do whenever std::initializer_list is present or not.</p> <ul> <li>If std::initializer_list is not present an implementation is provided.</li> <li>cpstd::intitlizer_list is only a template alias of std::intitializer_list</li> </ul> <p>minimal sketch with the solution:</p> <pre><code>#include &lt;Arduino.h&gt; #include &lt;stddef.h&gt; namespace std { template&lt;typename T&gt; class initializer_list { public: using value_type = T; using reference = const T&amp;; using const_reference = const T&amp;; using size_type = size_t; using const_iterator = const T*; private: const_iterator _M_array; size_type _M_len; constexpr initializer_list(const T* array, size_type size) noexcept : _M_array(array), _M_len(size) {} public: constexpr initializer_list() noexcept : _M_array(nullptr), _M_len(0) {} constexpr size_type size() const noexcept { return _M_len; } constexpr const_iterator begin() const noexcept { return _M_array; } constexpr const_iterator end() const noexcept { return _M_array + _M_len; } }; } namespace cpstd { template&lt;class T&gt; using initializer_list = std::initializer_list&lt;T&gt;; } template&lt;typename T&gt; class exampleClass{ protected: T buffer[10]; size_t len; public: exampleClass(): len(0) {} exampleClass(cpstd::initializer_list&lt;T&gt; il){ len = il.size(); for(size_t i = 0; i &lt; len; i++){ buffer[i] = *(il.begin()+i); } } exampleClass&amp; operator=(cpstd::initializer_list&lt;T&gt; il){ len = il.size(); for(auto i = il.begin(); i &lt; il.end(); i++){ buffer[i] = *i; } } size_t size() const {return len;} T data(size_t x) const {return buffer[x];} }; void setup() { // put your setup code here, to run once: Serial.begin(115200); exampleClass&lt;uint8_t&gt; myObject = {0,1,2,3}; Serial.println(myObject.size()); Serial.println(myObject.data(0)); Serial.println(myObject.data(1)); Serial.println(myObject.data(2)); Serial.println(myObject.data(3)); } void loop() { // put your main code here, to run repeatedly: } </code></pre>