Created
January 11, 2022 23:22
-
-
Save theKlanc/5943525d38695a6b8d40c7e332a8419c to your computer and use it in GitHub Desktop.
Code to use an ATTiny as an ADC using https://github.com/MCUdude/MicroCore
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| const int pulsePin = 4; | |
| const analog_pin_t readPin = A3; | |
| //const unsigned pulseWidthMicros = 10000; | |
| const unsigned pulseWidthMicros = 3000; | |
| void setup() { | |
| pinMode(pulsePin, OUTPUT); | |
| digitalWrite(pulsePin, LOW); | |
| pinMode(readPin, INPUT); | |
| } | |
| void writeBit(bool bit, int pin){ | |
| digitalWrite(pin, HIGH); | |
| delayMicroseconds(pulseWidthMicros); | |
| digitalWrite(pin, bit); | |
| delayMicroseconds(pulseWidthMicros); | |
| digitalWrite(pin, LOW); | |
| delayMicroseconds(pulseWidthMicros); | |
| } | |
| void writeSync(int pin){ | |
| writeBit(LOW, pin); | |
| digitalWrite(pin, HIGH); | |
| delayMicroseconds(pulseWidthMicros); | |
| delayMicroseconds(pulseWidthMicros); | |
| delayMicroseconds(pulseWidthMicros); | |
| digitalWrite(pin, LOW); | |
| delayMicroseconds(pulseWidthMicros); | |
| } | |
| bool calculateParity(int16_t data){ | |
| bool result = false; | |
| for(int i = 0; i < 16; ++i){ | |
| ┊ if(data & 0b1){ | |
| ┊ ┊ result = !result; | |
| ┊ } | |
| ┊ data = data >> 1; | |
| } | |
| return result; | |
| } | |
| void writeData(int16_t data, int pin){ | |
| bool parity = calculateParity(data); | |
| writeSync(pin); | |
| for(int i = 0; i < 16; ++i){ | |
| ┊ writeBit(data & 0b1, pin); | |
| ┊ data = data >> 1; | |
| } | |
| writeBit(parity, pin); | |
| } | |
| void loop() { | |
| delayMicroseconds(pulseWidthMicros * 3); | |
| int16_t battLvl = analogRead(readPin); | |
| writeData(battLvl, pulsePin); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment